Ninja420
Ninja420

Reputation: 3872

How do you safely free memory?

The code given below is giving undefined behaviour, sometimes the code runs well, but sometimes it gives a munmap_chunk error.

char *str = "hello world";
if(str != NULL) free(str)

Is there something wrong I am doing in the above code ?

Also how to avoid duplicate free ? How do I check if the variable has some memory right now / or has not been freed before ?

Upvotes: 0

Views: 101

Answers (3)

Jeegar Patel
Jeegar Patel

Reputation: 27200

Typically the string literal ("hello world") will be stored in the data section, in a read-only page.

So you can not free them.

Also how to avoid duplicate free ?

free() will free pointed memory but will not make pointer as NULL.After every free() make pointer as NULL.

if(str != NULL)
{
 free(str);
 str = NULL;
}

Upvotes: 2

Balu
Balu

Reputation: 2447

char *str = "hello world"; if(str != NULL) free(str);

It is wrong, *str is not malloced. and "hello world" is stored in read only memory, you can't free it

Upvotes: 0

Wyzard
Wyzard

Reputation: 34563

That string wasn't allocated with malloc(), so it shouldn't be freed with free(). String literals are allocated statically in your executable, not dynamically at runtime.

Upvotes: 1

Related Questions