How sizeof (* NULL) is 1 on a 32-bit C compiler?

I recently found out that sizeof not a function and actually estimates compilation time.

But I still could not figure out how sizeof(*NULL) is 1.

EDIT: I am talking specifically about gcc here.

+5
source share
4 answers

It depends on the compiler and the standard library. Using 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 will throw an error.

The standard library can also define NULL as 0 . In this case, sizeof(*NULL) will also be illegal.

+10
source

The standard does not give any guarantees regarding the value returned by sizeof(*NULL) , which is enough not to use this construct in practice.

Your code uses implementation-defined behavior.

7.173 Macros

 NULL 

which expands to a null pointer constant defined by the implementation

This means that the standard does not guarantee that your code will compile, let alone create a specific value.

On systems defining a NULL macro as ((void*)0) , your code will raise a warning, which should be considered an error:

prog.c: 4: 28: error: invalid application 'sizeof for type void [-Werror = pointer-arith]

Demo version

+3
source

Since NULL is of type void * , this means that *NULL is of type void . The void size is not allowed by the C standard, although some compilers do this as an extension.

In GCC, it treats the void size as 1 to allow pointer arithmetic to void * .

+2
source

In the "old time" NULL is defined as:

 #define NULL ((char *)0) 

therefore, with *NULL you get a char whose size is 1. (You can still see such a definition hidden in the headers as a return case, now, starting with C90, char is replaced with void ).

I don't think this is valid code (NULL indirectness, but also just size).

Some null compilers have 0l or just 0 , which will give an error in your case.

+1
source

Source: https://habr.com/ru/post/1276136/


All Articles