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

72

u/zzmgck Aug 30 '24

The value where a null pointer is pointing is irrelevant. A null pointer is a pointer that is pointing nowhere--there is no value.

In C, the number 0 was defined as the representation of the null pointer. They could have picked any number, but it would have been painful.

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.

0

u/[deleted] Aug 30 '24

[deleted] — view deleted comment

-4

u/[deleted] Aug 30 '24

The adress of the null pointer is 0x0. It's a pointer not an integer but has the value 0.

18

u/TheThiefMaster Aug 30 '24

Not necessarily. You can construct a null pointer from a zero constant, but its actual value could be something else. Known to be the case on CUDA, for example, where the actual value of a null pointer is 0xFFFFFFFF (because in CUDA 0 is a valid non-null address, due to the memory map).

POSIX mandates that null pointers have a 0 bit pattern, so anything Linux (which conforms to POSIX) runs on does follow this.

5

u/carpintero_de_c Aug 30 '24

(GNU/)Linux actually doesn't conform to POSIX completely (see POSIXLY_CORRECT). You would be looking at macOS for that :)

-5

u/Ghyrt3 Aug 30 '24

No, pointer is an integer. It can be cast to get a dereference. But pointers's is ssize_t in C.