是否需要将free()参数强制转换为void *? [英] Is casting free() argument to void * neccessary?

查看:408
本文介绍了是否需要将free()参数强制转换为void *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it neccessary to cast the value passed to free() to a void pointer in this code snippet?

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

np是链接列表中的struct,而defnchar *.

np is a struct in a linked list and defn is a char *.

推荐答案

C11:7.23.2.3免费功能

简介

#include <stdlib.h>
void free(void *ptr);  

这意味着它可以将指针带到任何类型(void *是通用指针类型).通常,无需将参数强制转换为void *,但在类似

It means that it can take pointer to any type (void * is a generic pointer type). In general no need to cast the argument to void *, but in cases like

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 *);
       ^

要取消显示此警告,需要强制转换

To suppress this warning a cast is needed

 free((void *)a);

这篇关于是否需要将free()参数强制转换为void *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆