What Is the Size of Void

What is the size of void?

The type void has no size; that would be a compilation error. For the same reason you can't do something like:

void n;

EDIT.
To my surprise, doing sizeof(void) actually does compile in GNU C:

$ echo 'int main() { printf("%d", sizeof(void)); }' | gcc -xc -w - && ./a.out 
1

However, in C++ it does not:

$ echo 'int main() { printf("%d", sizeof(void)); }' | gcc -xc++ -w - && ./a.out 
<stdin>: In function 'int main()':
<stdin>:1: error: invalid application of 'sizeof' to a void type
<stdin>:1: error: 'printf' was not declared in this scope

The size of void

In C pointer arithmetic is not defined for void pointers. Pointer arithmetic is intrinsically tied to the size of the pointed type. And for void * the size of the pointed type is unknown.

To see how pointer arithmetic works for different objects, try this:

int obj[5];
int *ip = obj;
char *cp = (char *)obj;

ip++;
cp++;

printf("%p\n%p\n", ip, cp);

However, if the compiler does support it, pointer arithmetic on void pointers works the same as on char pointers.

c: size of void*

Only data pointers. void * can hold any data pointer, but not function pointers.

Here is a C FAQ.

void *'s are only guaranteed to hold object (i.e. data) pointers; it
is not portable to convert a function pointer to type void *. (On some
machines, function addresses can be very large, bigger than any data
pointers.)

As for the first part, yes, different types can have pointers of different sizes:

C | find the size of the value a void Pointer is pointing at using sizeof()

The value of pointer merely conveys the starting address of an object, not any information about its size.

The type of a pointer inherently conveys information about the size of the object it points to, if it is a complete type. However, void is incomplete, and a void * provides no information about the size of the object it originated from (except possibly by extensions to standard C and by debugging features).

Generally, if your program needs to know the size of what a void * points to, it must track that information itself.

Why does sizeof(void) == 1?

sizeof(void) will not compile on a C compiler.

ISO 9899:2011 6.2.5/19

"The void type comprises an empty set of values; it is an incomplete
object type that cannot be completed."

ISO 9899:2011 6.5.3.4/1

"The sizeof operator shall not be applied to an expression that has function type or an
incomplete type"

This is normative text: sizeof(void) is not valid C.



Related Topics



Leave a reply



Submit