For example:
char * myString = malloc(sizeof(char)*STRING_BUFFER_SIZE); free(myString); free(myString);
Are there any adverse side effects of doing this?
“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.
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).
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.
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.
Here's the chapter and verse.
If the argument [to the
free
function] does not match a pointer earlier returned by thecalloc
,malloc
, orrealloc
function, or if the space has been deallocated by a call tofree
orrealloc
, the behavior is undefined. (ISO 9899:1999 - Programming languages — C, Section 7.20.3.2)
One of nothing, silent memory corruption, or segmentation fault.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With