c - 是否需要将 free() 参数转换为 void *?

标签 c malloc free

是否有必要将传递给 free() 的值转换为这段代码片段中的空指针?

free((void *) np->defn);

np 是链表中的 structdefnchar *

最佳答案

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/

相关文章:

c - "Semantic issue: Implicitly declaring library function ' malloc ' with type ' void *(无符号长)'"

c - 在 C 中是否可以在不移动它的情况下缩小分配的内存?

C++ double free or corruption (out) 错误

c - malloc 如何获取比分配更多的数据字节数

c - 传递矩阵作为参数

随身携带 C 编译器

c - 如何在 Linux 中等待一个程序的多个实例完成?

检查 Unix 消息队列是否为空

c - malloc() 中的双倍大小

c - 使用 realloc() 函数重新分配内存后如何添加数据?