What is the size of void?
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.
Solution 1:
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
Solution 2:
If you are using GCC and you are not using compilation flags that remove compiler specific extensions, then sizeof(void)
is 1. GCC has a nonstandard extension that does that.
In general, void
is a incomplete type, and you cannot use sizeof for incomplete types.
Solution 3:
Although void
may stand in place for a type, it cannot actually hold a value. Therefore, it has no size in memory. Getting the size of a void
isn’t defined.
A void
pointer is simply a language construct meaning a pointer to untyped memory.
Solution 4:
void
has no size. In both C and C++, the expression sizeof (void)
is invalid.
In C, quoting N1570 6.5.3.4 paragraph 1:
The
sizeof
operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member.
(N1570 is a draft of the 2011 ISO C standard.)
void
is an incomplete type. This paragraph is a constraint, meaning that any conforming C compiler must diagnose any violation of it. (The diagnostic message may be a non-fatal warning.)
The C++ 11 standard has very similar wording. Both editions were published after this question was asked, but the rules go back to the 1989 ANSI C standard and the earliest C++ standards. In fact, the rule that void
is an incomplete type to which sizeof
may not be applied goes back exactly as far as the introduction of void
into the language.
gcc has an extension that treats sizeof (void)
as 1. gcc is not a conforming C compiler by default, so in its default mode it doesn't warn about sizeof (void)
. Extensions like this are permitted even for fully conforming C compilers, but the diagnostic is still required.