In C, why do some people cast the pointer before freeing it?
Pre-standard C had no void*
but only char*
, so you had to cast all parameters passed. If you come across ancient C code, you might therefore find such casts.
Similar question with references.
When the first C standard was released, the prototypes for malloc and free changed from having char*
to the void*
that they still have today.
And of course in standard C, such casts are superfluous and just harm readability.
Casting may be required to resolve compiler warnings if the pointers are const
. Here is an example of code that causes a warning without casting the argument of free:
const float* velocity = malloc(2*sizeof(float));
free(velocity);
And the compiler (gcc 4.8.3) says:
main.c: In function ‘main’:
main.c:9:5: warning: passing argument 1 of ‘free’ discards ‘const’ qualifier from pointer target type [enabled by default]
free(velocity);
^
In file included from main.c:2:0:
/usr/include/stdlib.h:482:13: note: expected ‘void *’ but argument is of type ‘const float *’
extern void free (void *__ptr) __THROW;
If you use free((float*) velocity);
the compiler stops complaining.