Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 583
Lakshmi Avatar asked Nov 03 '09 09:11

Lakshmi


People also ask

What is the range of void in C?

It's capable of storing at least −9,223,372,036,854,775,807 to 9,223,372,036,854,775,807. Alternatively, get even more overkill with unsigned long long , which will give you at least 0 to 18,446,744,073,709,551,615.

How much bytes of memory does void occupy?

How much bytes of memory does void occupy? void does not occupy any memory. Hence, it takes 0 bytes of memory.

What is void * in C?

The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means that it points to the address of variables. It is also called the general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.

What is a void data type?

void data type. A data type that has no values or operators and is used to represent nothing.


1 Answers

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 
like image 151
reko_t Avatar answered Sep 24 '22 00:09

reko_t