different clang and gcc behavior with pointers

312 views Asked by At

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:

  1. What is the normal behavior according to the C standard (and C++)?
  2. Why does this happen?
2

There are 2 answers

0
Spikatrix On BEST ANSWER

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.

1
TartanLlama On

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;