将free()参数转换为void*neccessary?

CS *_*ent 2 c malloc free

是否需要将传递给该值的值转换free()为此代码段中的void指针?

free((void *) np->defn);
Run Code Online (Sandbox Code Playgroud)

np是一个struct链接列表,defn是一个char *.

hac*_*cks 5

C11:7.22.3.3自由功能

概要

#include <stdlib.h>
void free(void *ptr);  
Run Code Online (Sandbox Code Playgroud)

这意味着它可以将指针指向任何类型(void *是通用指针类型).一般来说,不需要将参数强制转换为void *,但是在类似的情况下

int const *a = malloc(sizeof(int));
free(a);
Run Code Online (Sandbox Code Playgroud)

编译器会生成一个waring

test.c: In function 'main':
test.c:33:7: warning: passing argument 1 of 'free' discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
  free(a);
       ^
In file included from test.c:2:0:
/usr/include/stdlib.h:151:7: note: expected 'void *' but argument is of type 'const int *'
 void  free(void *);
       ^
Run Code Online (Sandbox Code Playgroud)

要禁止此警告,需要进行强制转换

 free((void *)a);
Run Code Online (Sandbox Code Playgroud)