Trying to free the allocated memory
two times
causes undefined behavior. The following example shows the wrong usage of two
free statements
:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("Allocating memory...\n");
int *p = malloc(sizeof(int));
*p = 123;
printf("The value is: %d\n", *p);
printf("Freeing twice - undefined behavior.\n");
free(p);
free(p); // undefined behavior
}
Possible Output:Allocating memory...
The value is: 123
Freeing twice - undefined behavior.
free(): double free detected in tcache 2