In the following code, delete[]
is called once to free up the memory allocated by new
. However, the array elements is still accessible after delete[]
is called. I called delete[]
twice to confirm that I am getting a double free or corruption
error, which I am getting, which means the memory is freed. If the memory is freed, how am I able to access the array elements? Could this be a security issue which might be exploited, if I am reading something like a password into the heap?
int *foo;
foo = new int[100];
for (int i = 0; i < 100; ++i) {
foo[i] = i+1;
}
cout << foo[90] << endl;
delete[] foo;
cout << foo[90] << endl;
gives the following output
91
91
and
int *foo;
foo = new int[100];
for (int i = 0; i < 100; ++i) {
foo[i] = i+1;
}
cout << foo[90] << endl;
delete[] foo;
delete[] foo;
cout << foo[90] << endl;
gives
*** Error in
./a.out': double free or corruption (top): 0x000000000168d010 ***`