I am new to this particular forum, so if there are any egregious formatting choices, please let me know, and I will promptly update.
In the book C Programming: A Modern Approach (authored by K. N. King), the following passage is written:
If a pointer variable
p
hasn't been initialized, attempting to use the value ofp
in any way causes undefined behavior. In the following example, the call ofprintf
may print garbage, cause the program to crash, or have some other effect:int *p; printf("%d", *p);
As far as I understand pointers and how the compiler treats them, the declaration int *p
effectively says, "Hey, if you dereference p
in the future, I will look at a block of four consecutive bytes in memory, whose starting address is the value contained in p
, and interpret those 4 bytes as a signed integer."
As to whether or not that is correct...if it is correct, then I am a little confused about why the aforementioned block of code:
- is classified as undefined behavior
- can cause programs to crash
- can have some other effect
Commenting on the above-numbered cases:
My understanding of undefined behavior is that, at run time, anything can happen. With that being said, in the above code it appears to me that only a very defined subset of things can happen. I understand that p
(due to its lack of initialization) is storing a random address that could point anywhere in memory. However, when printf
is passed the dereferenced value *p
, won't the compiler just look at the 4 consecutive bytes of memory (which start at whatever random address) and interpret those 4 bytes as a signed integer?
Therefore, printf
should only do one thing: print a number that ranges anywhere from -2,147,483,648 to 2,147,483,647. Clearly that is a lot of different possible outputs, but does that really qualify as "undefined behavior". Further, how could such an "undefined behavior" lead to "program crash" or "have some other effect".
Any clarification would be greatly appreciated! Thanks!