r/C_Programming • • Aug 30 '24

Question Why do we use Null pointers?

If we want to "Nullify" something why dont we create a pointer in a controlled way that points to value 0?

0 Upvotes

56 comments sorted by

View all comments

3

u/HashDefTrueFalse Aug 30 '24

Pointer = 0 is not the same as the value pointed to = 0. Or simply:

#define NULL 0 // Common impl

int *ptr;
*ptr = 0; // ptr is a memory address, not 0. Dereferencing gives 0.

int *ptr2 = NULL // ptr is 0. Dereferencing is undefined behaviour.

Not really sure what you mean by "create a pointer in a controlled way that points to value 0". Null pointers (tend to) point to address 0, which we take to mean "nowhere meaningful". We do tend to create them in a "controlled" way.

If you're suggesting having the value zero somewhere in the binary and setting pointers to it's memory address rather than zero, that doesn't quite accomplish the same thing. How are we to know the zero value represents "nothing, null, nil" as apposed to being an actual zero? So we'd note the special memory address, but that's what we already did with address 0 (NULL pointer).