是否有必要将传递给 free()
的值转换为这段代码片段中的空指针?
free((void *) np->defn);
np
是链表中的 struct
,defn
是 char *
。
最佳答案
C11 : 7.22.3.3 自由函数
Synopsis
#include <stdlib.h> void free(void *ptr);
这意味着它可以接受指向任何类型的指针(void *
是通用指针类型)。通常不需要将参数强制转换为 void *
,但在像
int const *a = malloc(sizeof(int));
free(a);
编译器会生成警告
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 *);
^
要抑制此警告,需要强制转换
free((void *)a);
关于c - 是否需要将 free() 参数转换为 void *?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25339569/