0

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?
Null
  • 1,950
  • 9
  • 30
  • 33
  • 4
    In C++ using an [indeterminate value is undefined behavor](http://stackoverflow.com/q/23415661/1708801) and so the behavior is unpredictable and can vary. It is also undefined behavior in [C as well](http://blog.frama-c.com/index.php?post/2013/03/13/indeterminate-undefined). – Shafik Yaghmour Jun 10 '15 at 12:38
  • Cool Guy has the only correct answer. Just wanted to add that your compiler will report this kind of behavior. Try compiling with `-Wall` for either compiler... – Brian McFarland Jun 10 '15 at 13:02

2 Answers2

7

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.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
3

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;
TartanLlama
  • 63,752
  • 13
  • 157
  • 193