Welcome to Questionaries, where you can ask questions and receive answers from other members of the community.

Let us know at info@questionaries.org

Ask Question Why is address zero used for null pointer?

13 like 0 dislike
Hello,

In C (or C++ for that matter), pointers are special if they have the value zero: I am adviced to set pointers to zero after freeing their memory, because it means freeing the pointer again isn't dangerous; when I call malloc it returns a pointer with the value zero if it can't get me memory; I use if (p != 0) all the time to make sure passed pointers are valid etc.

But since memory addressing starts at 0, isn't 0 just as a valid address as any other? How can 0 be used for handling null pointers if that is the case? Why isn't a negative number null instead?


Thanks......................
asked 2 years ago by biswaskeran (70,430 points)

1 Answer

0 like 0 dislike
I think it's just a convention. There must be some value to mark an invalid pointer.

You just lose one byte of address space, that should rarely be a problem.

There are no negative pointers. Pointers are always unsigned. Also if they could be negative your convention would mean that you lose half the address space.
answered 2 years ago by lily (17,510 points)

Related questions

10 like 0 dislike
1 answer
4 like 0 dislike
1 answer
asked 1 year ago by daneim (127,080 points)
11 like 0 dislike
0 answers
asked 2 years ago by biswaskeran (70,430 points)
5 like 0 dislike
1 answer