What is the size of void?

Lakshmi picture Lakshmi · Nov 3, 2009 · Viewed 65.5k times · Source

What would this statement yield?

void *p = malloc(sizeof(void));

Edit: An extension to the question.

If sizeof(void) yields 1 in GCC compiler, then 1 byte of memory is allocated and the pointer p points to that byte and would p++ be incremented to 0x2346? Suppose p was 0x2345. I am talking about p and not *p.

Answer

reko_t picture reko_t · Nov 3, 2009

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