It would be a legacy thing!
Before there was a C standard, the free()
function would have been (implicitly) of type int
— because there was not yet reliably a type void
for it to return. There was no value returned.
When the code was first modified to work with standard C compilers, it probably didn't include <stdlib.h>
(because it didn't exist before the standard). Old code would write extern char *malloc();
(maybe without the extern
) for the allocation functions (similarly for calloc()
and realloc()
), and didn't need to declare free()
. And the code would then cast the return value to the correct type — because that was necessary on at least some systems (including the one I learned C on).
Sometime later, the (void)
cast was added to tell the compiler (or, more likely, lint
) that "the return value from free()
is deliberately ignored" to avoid a complaint. But it would have been better to add <stdlib.h>
and let its declaration extern void free(void *vp);
tell lint
or the compiler that there was no value to ignore.
JFTR: Back in the mid-'80s, the ICL Perq was originally on a word-oriented architecture and the char *
address for a memory location was a very different number from the 'anything_else pointer' to the same location. It was crucial to declare char *malloc()
somehow; it was crucial to cast the result from it to any other pointer type. The cast actually changed the number used by the CPU. (There was also much rejoicing when the main memory on our systems was upgraded from 1 MiB to 2 MiB — since the kernel used about 3/4 MiB, it meant that user programs could use 1 1/4 MiB before paging etc.)