I recently learned that sizeof
is not a function and actually evaluates at compile time.
But I still haven't been able to figure out how sizeof(*NULL)
is equal to 1.
EDIT: I'm talking about gcc here specifically.
NULL in C is defined as (void*)0. Since it's a pointer, it takes 4 bytes to store it. And, "" is 1 byte because that "empty" string has EOL character ('\0').
32 bit architectures are word aligned and byte referenced. It is irrelevant how the architecture stores a char, but to compiler, you must reference chars 1 byte at a time, even if they use up less than 1 byte. This is why sizeof(char) is 1.
Since NULL is defined as ((void*)0), we can think of NULL as a special pointer and its size would be equal to any pointer. If the pointer size on a platform is 4 bytes, the output of the above program would be 4.
In C, NULL is a macro that expands either to 0 or (void*)0 (or something that has a similar effect). In the first case, you can not differentiate between NULL and 0 , because they are literally the same.
It depends on the compiler and standard library. With GCC and glibc, NULL
is defined as (void*)0
and GCC has an extension that allows pointer arithmetic on void
pointers using sizeof(void) == 1
. Without this extension, the compiler would produce an error.
A standard library could also define NULL
as 0
. In this case sizeof(*NULL)
would also be illegal.
Standard makes no guarantee as to the value returned by sizeof(*NULL)
, which is enough to not use this construct in practice.
Your code uses implementation-defined behavior.
7.173 The macros are
NULL
which expands to an implementation-defined null pointer constant
This means that the standard does not guarantee that your code is going to compile, let alone producing a certain value.
On systems defining macro NULL
as ((void*)0)
your code will trigger a warning that should be treated as an error:
prog.c:4:28: error: invalid application of ‘sizeof’ to a void type [-Werror=pointer-arith]
Demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With