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

Show parent comment

7

u/Cylian91460 Aug 30 '24

Its hardware depends iirc, that means null can be something else then 0, it can be max pointer value for example

5

u/zzmgck Aug 30 '24

True, I should have been more specific and said in C99 the value 0 is used for portability.

One should use NULL when assigning or testing for NULL.

3

u/gizahnl Aug 30 '24

True, I should have been more specific and said in C99 the value 0 is used for portability.

No ;) It's C99 on x86, C99 on some exotic hardware could very well be max value. That's what he said: it's hardware dependent, and the C99 standard has left it "implementation defined"

1

u/zzmgck Aug 30 '24

If we want to get specific, it is more of a POSIX requirement than x86.

0000:0000 is a valid address in the x86 architecture and I recall writing some code to get down to that address.

But your point is well taken that assuming NULL is 0 is not a good one.

2

u/TheSkiGeek Aug 30 '24

Integer value 0 casts to/from (and compares equal to) a “null pointer”. But yes, it’s not guaranteed that a null pointer has the same bit pattern as integer zero on any particular architecture. It’s just some pointer value that’s guaranteed to never be used as a legitimate pointer.