我收到了这条消息:
expected 'void **' but argument is of type 'char **'
当我试图编译类似这样的东西时:
void myfree( void **v )
{
if( !v || !*v )
return;
free( *v );
*v = NULL;
return;
}
在阅读有关堆栈溢出的这个问题后,我发现了我认为的解决方案:
避免不兼容的指针警告在处理双重间接时 - 堆栈溢出
所以我调整为这样的内容:
#include <stdio.h>
#include <stdlib.h>
void myfree( void *x )
{
void **v = x;
if( !v || !*v )
return;
free( *v );
*v = NULL;
return;
}
int main( int argc, char *argv[] )
{
char *test;
if( ( test = malloc( 1 ) ) )
{
printf( "before: %p\n", test );
myfree( &test );
printf( "after: %p\n", test );
}
return 0;
}
这是合法的C吗?我正在取消引用一个 void 指针,不是吗?
谢谢大家
编辑 2010 年 12 月 10 日下午 4:45 EST:
正如已经指出的那样,它free(NULL)
是安全的并且被 C 标准覆盖。此外,如下所述,我上面的示例是不合法的 C。请参阅 caf 的答案、Zack 的答案和我自己的答案。
因此,我将更容易将任何要被 malloc 的指针初始化为 NULL,然后在代码中直接将 free() 和 NULL 初始化为:
free( pointer );
pointer = NULL;
我像以前一样在 myfree() 中检查 NULL 的原因是因为我使用 fclose() 的经验。fclose(NULL)
可以根据平台(例如 xpsp3 msvcrt.dll 7.0.2600.5512)发生段错误,所以我假设(错误地)同样的事情可能发生在 free() 上。我想,与其用 if 语句弄乱我的代码,我可以更好地在函数中实现。
谢谢大家的好讨论