1

When I have a code like this :

int* nPtr = 0;
MyClass* myClass = 0;

What compiler really does under the hood. I mean anyway there must be some place in memory to refer. Does compiler have a special memory block for null pointer to where all they refer ?

Puppy
  • 144,682
  • 38
  • 256
  • 465
NDeveloper
  • 1,837
  • 4
  • 20
  • 34

3 Answers3

2

I mean anyway there must be some place in memory to refer.

Nope. You can't dereference a NULL pointer and get an object. There's no object at memory location 0x0 *.

It's just a convention that we have this one [invalid] pointer value that we can use to identify a pointer as deliberately not pointing anywhere valid.


* - or whatever your implementation decides to use for a 0-pointer

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • I worked for a company that used `0xDEADBEEF` as its null pointer address. It made it very easy to find a null pointer reference when there was a core dump. – rcollyer Jun 29 '11 at 14:34
  • @rcollyer: I believe Visual Studio still fills its mapped memory area with `0xDEADBEEF` in debug mode to make it easier to identify uninitialised pointers. – Lightness Races in Orbit Jun 29 '11 at 14:35
  • @Tomalak: If not [MS](http://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations) – Martin York Jun 29 '11 at 15:32
  • @rcollyer: It was not your company more likely the compiler. 0xDeadBeef was used to indicate uninitialized memory. Initially done by the hardware (http://www.urbandictionary.com/define.php?term=0xDEADBEEF) But picked up by compiler on other Unix like platforms. – Martin York Jun 29 '11 at 15:35
  • @Martin, most likely your right. Since I was in test, I was not privy to the toolchain, only what I could glean from the more talkative developers. However it was set, this was left in the production code. – rcollyer Jun 29 '11 at 15:49
1

The only "handling" that the compiler does, is that 0 is not necessarily translated as the address memory 0. This is implementation specified.

The compiler will simply map this 0 to a specific address that cannot possibly be part of the process user space.

When trying to access an address outside of the process user space, the OS will typically "catch" the access and issue and error. On Unix systems, this is the infamous SEGFAULT.

Note that this very same error is also emitted for a pointer with a garbage value that points outside the process user space.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
0

A pointer is an adress to a location in your memory. In this case the adress is 0. It's pointing to the "zero location". When you try to access it, you get a Seg Fault. The compiler doesn't complain about it.

Alex
  • 365
  • 3
  • 11