Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

pointers

gcc

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.

like image 439
Utkarsh Agarwal Avatar asked Mar 28 '18 18:03

Utkarsh Agarwal


People also ask

What is the size of null in C?

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').

What is a sizeof char in a 32 bit C compiler?

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.

Does a NULL pointer have a size?

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.

Are 0 and null the same in C?

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.


2 Answers

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.

like image 160
nwellnhof Avatar answered Sep 26 '22 15:09

nwellnhof


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.

like image 38
Sergey Kalinichenko Avatar answered Sep 24 '22 15:09

Sergey Kalinichenko