Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you try to free() already freed memory in c?

For example:

char * myString = malloc(sizeof(char)*STRING_BUFFER_SIZE); free(myString); free(myString); 

Are there any adverse side effects of doing this?

like image 269
lillq Avatar asked Sep 25 '08 19:09

lillq


People also ask

What does freeing memory do in C?

“free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place.

What happens if I don't free memory in C?

If free() is not used in a program the memory allocated using malloc() will be de-allocated after completion of the execution of the program (included program execution time is relatively small and the program ends normally).

What happens if you call free on stack memory?

This is a bug. free() frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is NULL, no operation is performed.

What happens if you free without malloc?

free() uses data prepended to the allocated block to manage the heap. If the memory pointed to was not allocated by a heap allocation function such as malloc() or calloc(), then the data preceeding the block will be meaningless as heap management data.


2 Answers

Here's the chapter and verse.

If the argument [to the free function] does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined. (ISO 9899:1999 - Programming languages — C, Section 7.20.3.2)

like image 192
Chris Conway Avatar answered Oct 03 '22 05:10

Chris Conway


One of nothing, silent memory corruption, or segmentation fault.

like image 23
mbac32768 Avatar answered Oct 03 '22 03:10

mbac32768