Maestro
Maestro

Reputation: 9508

Freeing global variable

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?

Upvotes: 1

Views: 6305

Answers (2)

ouah
ouah

Reputation: 145829

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.

Upvotes: 4

simonc
simonc

Reputation: 42175

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

Upvotes: 8

Related Questions