Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

free() syntax with arguments in C

I am working on converting many C programs from Unix to Linux and this free() syntax caught my attention:

free((char *) area );

What's the difference between this and free( area ); ?

like image 675
user3772839 Avatar asked Oct 04 '14 12:10

user3772839


2 Answers

The signature of free is:

void free(void *ptr);

So if area is a pointer type that is returned by malloc or its cousins, the conversion in free((char *) area ); is pointless.

Unless... if the code is really, really old, that is, before ANSI C introduced void * as generic pointer. In that ancient time, char * is used as generic pointer.

like image 104
Yu Hao Avatar answered Oct 13 '22 22:10

Yu Hao


If someone were storing a pointer to dynamic allocated data in a non-pointer type sanctioned by the standard, i.e. area is declared as intptr_t for example, this casts the non-pointer to a pointer type and allows it to be freed.

If area is already a pointer type, this makes no sense at all with any C code written in the last quarter-century.

like image 39
WhozCraig Avatar answered Oct 13 '22 22:10

WhozCraig