Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c: size of void*

I'm a bit confused with a void* pointer in C. Especially after reading this question: Is the sizeof(some pointer) always equal to four?, where one person says there is no guarantee that sizeof(int *) == sizeof(double *)

My question is: is there a guarantee of sizeof(void*) >= sizeof(any other pointer type)? In other words, can I always assign a some_type* pointer to a void* pointer and then get it back as some_type*?

like image 691
facha Avatar asked Aug 02 '11 07:08

facha


People also ask

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.

How big is a void pointer?

The size of a void pointer is different in different systems. In 16-bit systems, the size of a void pointer is 2 bytes. In a 32-bit system, the size of a void pointer is 4 bytes. And, in a 64-bit system, the size of a void pointer is 8 bytes.

Why is sizeof void 1?

When you do pointer arithmetic adding or removing one unit means adding or removing the object pointed to size. Thus defining sizeof(void) as 1 helps defining void* as a pointer to byte (untyped memory address).

Can you free a void * in C?

yes it is safe. Show activity on this post. In one case, malloc and free match, and in the other the allocated memory is returned. There are also secondary resources, and the constructor and destructor match.


1 Answers

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:

like image 90
cnicutar Avatar answered Sep 18 '22 19:09

cnicutar