This is the code I have currently.
int main() {
double *t, *k;
Item *a = calloc(1, sizeof(Item));
a->w = malloc(sizeof(double));
t = a->w;
k = t;
free(a->w);
free(a);
free(k);
return 0;
}
In this example, I was able to compile and run without getting any explicit errors. However if I free the pointer, k, before the structure, a, is freed, then I receive a double free/heap corruption error.
free(a->w);
free(k);
free(a);
Additionally, I receive the same error if I do:
free(k);
free(a->w);
free(a);
Why is it that I can free the pointer, k after the structure has been freed without any explicit errors, but I cannot free the memory k is pointing twice until the structure a is freed?
This is an example of Undefined behavior. This means anything can happen, such as appearing to work, crashing immediately, crashing at some point later, or strange unexpected behavior, or the often mentioned nasal demons.
From the man page:
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.
So triggering a double-free error may occur but is not required.