C++ pointer array is still accessible after delete

2020-02-16 03:37发布

问题:

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 ***`

回答1:

The memory is free, which means it isn't attributed anymore, but the compiler's not going to take the extra effort to wipe it back to 0 everytime something's deleted.

It's also not going to take the effort to check that the memory is properly allocated before you access it - it'd reduce performance, and it assumes you don't do so. (Although tools like valgrind or debuggers can detect those wrong calls)

So it just changes the range of the memory as 'unassigned' internally, which means another call to new can use that same memory range. Then whatever data in that memory would be overwritten, and foo[90] won't return the same thing anymore.