Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to free 'void*'?

Tags:

c

Consider:

struct foo {     int a;     int b; };  void* p = (void*)malloc(sizeof(struct foo)); ((foo*)p)->a; // Do something. free(p); // Is this safe? 
like image 597
CodingLab Avatar asked Feb 02 '10 05:02

CodingLab


2 Answers

Yes.

malloc returns void * and free takes void *, so some of your casts are meaningless, and you're always freeing a void * even if you're starting with some other sort of pointer.

like image 157
Laurence Gonsalves Avatar answered Oct 06 '22 00:10

Laurence Gonsalves


Yes, it's safe. When allocating memory, the runtime library keeps track of the size of each allocation. When you call free(), it looks up the address, and if it finds an allocation for that address, the correct amount of memory is freed (the block that was allocated at that address).

like image 41
Pepor Avatar answered Oct 05 '22 23:10

Pepor