问题
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