Why cast free's return value to void?

Adam Johnston :

I am reading a book (Programming with POSIX Threads by Butenhof, 1997) that uses C, and I came across the following line:

(void)free(data);

Here, data is just a pointer to an allocated struct,

data = malloc(sizeof(my_struct_t));

Why is the result of free being cast to void?

From my understanding of C, this doesn't seem to make sense for two reasons:

  • The free function already returns void
  • The code is not using the return value (it's not even being assigned to a variable)

The book was written in 1997. Is this some sort of legacy thing?

The author mentions that the examples were run on Digital Unix 4.0d, but I still can't imagine a reason to ever cast the result of a function if you're not going to use that result.

Eugene Sh. :

If we are talking about the standard free function then its prototype is

void free(void *ptr);

Therefore the cast is completely useless.
Now some speculation.

The author might have forgotten to include the stdlib.h header declaring this prototype, so the compiler is assuming the return type of it as int. Now during static analysis of this code the compiler was warning about the unused return value of what it thinks to be a non-void function. Such a warnings are usually silenced by adding the cast to void.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=278866&siteId=1