NDeveloper
NDeveloper

Reputation: 1847

How compilers are handling null pointers

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 ?

Upvotes: 1

Views: 205

Answers (3)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

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

Upvotes: 2

Matthieu M.
Matthieu M.

Reputation: 299820

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.

Upvotes: 1

Alex
Alex

Reputation: 365

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.

Upvotes: 0

Related Questions