【发布时间】:2011-05-13 15:48:39
【问题描述】:
gcc 4.4.5 c89
我有一个名为 create_object 的函数,我在其中为全局结构分配内存。我有一个名为destroy_object 的函数,我在其中检查指针是否为空,然后释放。以防我释放尚未分配的内存。但是,我已经通过连续两次调用destroy_object 对此进行了测试。但是,我在第二次调用时得到了堆栈转储。但是,我确信它不会释放,因为我已将指针分配给 NULL。所以它应该跳过免费功能。
static struct Config_t {
char protocol[LINE_SIZE];
char mode[LINE_SIZE];
} *app_cfg = NULL;
int create_object()
{
app_cfg = malloc(sizeof *app_cfg);
memset(app_cfg, 0, sizeof *app_cfg);
}
void destroy_config()
{
/* Check to see if the memory is ok to free */
if(app_cfg != NULL) {
free(app_cfg);
app_cfg = NULL;
}
}
非常感谢您的任何建议,
================== 编辑========== 基本上我在我的主函数中有一个对 create_object() 的调用,我做了一些处理,然后调用了 destory_object。
int main(void)
{
create_object();
/* Do some processing on the structure */
destroy_object();
return 0;
}
==========================最终编辑==== 静态结构 Config_t { 字符协议[LINE_SIZE]; 字符模式[LINE_SIZE]; } app_cfg[1] {{"", ""}};
现在我没有使用 malloc 和 free。
【问题讨论】:
-
这对我来说很好,你能发布使用这个指针并调用
create_object和destroy_config的代码吗?此外,如果您想立即将分配给app_cfg的内存初始化为0,您可以将malloc和memset调用合并为一个calloc调用。此外,空指针上的free非常好。 -
将空指针传递给
free()是一个安全的空操作,因此您不需要在destroy_config()中进行空检查。 -
你能通过gdb运行代码并查看SIGSEGV引发后的回溯吗?它是否指向您程序中的任何其他位置?