Freeing global variable

元气小坏坏 提交于 2019-12-20 06:15:10

问题


Suppose I have a global variable that contains a large structure:

typedef struct {
    char Big[1024]
} LARGE;

static LARGE x;

void main()
{
     free(x);
}

Can I safely call free(x) from main when I dont need it anymore?


回答1:


No. You didn't dynamically allocate x so don't need to (and cannot) free it.

If you absolutely need to free the memory before your program exits, declare a pointer as global, allocate it on demand, using malloc or calloc, then free it when you're finished with the structure.

static LARGE* x;

void main()
{
    x = malloc(sizeof(*x));
    // use x
    free(x);
}



回答2:


No, free can only be used to deallocate objects that have been allocated through a call to malloc.

Objects with static storage duration can only be deallocated when the program exits.



来源:https://stackoverflow.com/questions/14429389/freeing-global-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!