首页 文章

释放分配的内存

提问于
浏览
1

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;
    }
}

非常感谢任何建议,

=================编辑==========基本上我在我的main函数中调用了create_object()并且我做了一些处理然后做了一个调用destory_object .

int main(void)
{
    create_object();

    /* Do some processing on the structure */

    destroy_object();

    return 0;
}

========================= Final Edit ==== static struct Config_t {char protocol [LINE_SIZE];字符模式[LINE_SIZE]; } app_cfg [1] {{“”,“”}};

现在我没有使用malloc和free .

2 回答

  • 2

    我只有一个建议 . 不要为此分配内存,这是浪费精力 .

    由于 app_cfg 是文件级变量,因此无论如何一次只能有一个副本,因此分配和取消分配它没什么意义 .

    只需将其创建为静态非指针并使用它:

    static struct Config_t {
        char protocol[LINE_SIZE];
        char mode[LINE_SIZE];
    } app_cfg;
    

    你仍然可以提供 createdestroy ,其中 memset 结构为零,但即使这样也可能不需要:

    void create_object (void) {
        memset(&app_cfg, 0, sizeof(app_cfg));
    }
    
    void destroy_config (void) {
        memset(&app_cfg, 0, sizeof(app_cfg));
    }
    
  • 3

    当我调用它两次时,在Cygwin下使用gcc 3.3.3的代码可以正常工作 . 你没有告诉我们你在这些功能之外做了什么,所以先看看,例如也许你不小心在调用之间给app_cfg分配了一个垃圾非NULL值 . 另外,如果你没有使用“大名”编译器,那么这可能是编译器错误(例如,它在编译时可能过于乐观,并假设你永远不会将NULL传递给destroy_config) . 尝试加入类似的东西:

    void destroy_config()
    {
    
        /* Check to see if the memory is ok to free */
        if(app_cfg != NULL) {
            printf("not null\n" );
            free(app_cfg);
            app_cfg = NULL;
        }else{
            printf("null\n" );
            }
    }
    

    看它是否真的“知道”何时为空 .

相关问题