I was reading a textbook which describes a common mistake when dealing with dynanmic memory allocation, below is the buggy code:
int *heapref(int n, int m)
{
int i;
int *x, *y;
x = (int *)malloc(n * sizeof(int)); //line 6
.
. // Other calls to malloc and free
.
free(x); //line 10
y = (int *)Malloc(m * sizeof(int)); //line 12
for (i = 0; i < m; i++)
y[i] = x[i]++; /* Oops! x[i] is a word in a free block */
return y;
}
And the author says:
Depending on the pattern of
malloc
andfree
calls that occur between lines 6 and 10, when the program referencesx[i]
in line 14, the array x might be part of some other allocated heap block and may have been overwritten
I'm a little bit confused here, the only thing that can cause issue to me is the line 12 which allocates a new memory block after free(x)
, if I comment out line 12, then the program will still function correctly by luck, isn't it? How does malloc
and free
calls that occur between lines 6 and 10 affect sth that actually happen after itself?