gcc 4.4.5 c89釋放分配的內存
我有一個名爲create_object的函數,其中我爲全局結構分配內存。我有一個名爲destroy_object的函數,我檢查指針是否爲空,然後我釋放。只需要我釋放尚未分配的內存。不過,我已經通過連續調用2次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;
}
}
非常感謝您的任何建議,
=================編輯========== Basicially我在我的主函數調用了create_object(),我做了一些處理,然後調用destory_object。
int main(void)
{
create_object();
/* Do some processing on the structure */
destroy_object();
return 0;
}
=========================最終編輯==== 靜態結構Config_t { 炭協議[LINE_SIZE]; char mode [LINE_SIZE]; } app_cfg [1] {{「」,「」}};
現在我不使用malloc和免費。
對我來說看起來不錯,你可以發佈使用這個指針的代碼並調用'create_object'和'destroy_config'嗎?另外,如果你想立即將分配給'app_cfg'的內存初始化爲0,你可以將你的'malloc'和'memset'調用合併成一個'calloc'調用。另外,空指針上的'free'非常好。 – birryree 2010-11-22 05:46:08
將空指針傳遞給'free()'是一個安全的無操作,所以你不需要'destroy_config()'中的空檢查。 – Wyzard 2010-11-22 05:49:58
是否可以通過gdb運行代碼並在SIGSEGV引發後查看回溯?它指向程序中的任何其他地方嗎? – vpit3833 2010-11-22 06:10:03