Reputation: 3
For example, we have the following simple code:
#include "stdio.h"
int main() {
int* pointer_to_check;
printf("%x\n", pointer_to_check);
return 0;
}
With gcc, we will get zero at output (as for me, normal behavior, because pointer isn't associated with memory), but clang gives us a real address, which can be accessed without "segmentation fault".
I have two questions:
Upvotes: 0
Views: 278
Reputation: 20244
pointer_to_check
to check is uninitialized. It points to some "random" location.
Accessing uninitialized variables leads to Undefined Behavior which means that anything can happen.
Also, pointers should be printed using the %p
format specifier.
with gcc code, we will get zero at output
Anything can be the output. It is Undefined. You shouldn't rely on this behavior.
Upvotes: 7
Reputation: 65600
This is undefined behaviour.
Pointers are not initialized when you declare them, so they could point anywhere. 0
, 0xDEADBEEF
or anything else are "valid" representations.
If you want the pointer to be initialized to null, do it explicitly:
int* pointer_to_check = nullptr;
Upvotes: 3