繁体   English   中英

释放分配的内存

[英]freeing allocated memory

gcc 4.4.5 c89

我有一个名为create_object的函数,在其中为全局结构分配内存。 我有一个名为destroy_object的函数,在该函数中检查指针是否为null,然后释放。 万一我释放了尚未分配的内存。 但是,我已经通过连续两次调用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 {char protocol [LINE_SIZE]; 字符模式[LINE_SIZE]; } app_cfg [1] {{“”,“”}};

现在,我不使用malloc和free。

我只有一个建议。 不要为此分配内存,这是浪费时间。

由于app_cfg是文件级变量,因此您一次只能拥有一个副本,因此分配和取消分配它毫无意义。

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

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

您仍然可以提供一个createdestroymemset结构为零,但即使这样可以不要求:

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

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

当我两次调用它时,在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" );
        }
}

查看它是否为空时是否真的“知道”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM