What will happen if someone tries to access freed memory? |
What exactly will happen depends on the compiler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
int main ()
{
short* short_ptr = new short{12};
std::cout << short_ptr << ",\t" << *short_ptr << "\n\n";
delete short_ptr;
long* long_ptr = new long{123456};
std::cout << short_ptr << ",\t" << *short_ptr << "\n";
std::cout << long_ptr << ",\t" << *long_ptr << "\n\n";
*short_ptr = 125; // uh-oh!
std::cout << short_ptr << ",\t" << *short_ptr << "\n";
std::cout << long_ptr << ",\t" << *long_ptr << "\n";
}
|
The example above compiles in both TDM GCC 4.9.2 and MS Visual C++ 2015 Community. Differences occur when running the resulting executable.
TDM GCC produces the following output:
0x182510, 12
0x182510, -7616
0x182510, 123456
0x182510, 125
0x182510, 65661 |
MSVC++ produces the following output:
And then crashes with a "read access violation." Writing to a deleted pointer would also crash,
*short_ptr = 125;
, with a "write access violation" if the program had not already terminated.
One thing to note is that
new
assigns memory addresses differently between TDM GCC and MSVC++. MSVC++ may not assign the same memory location to a new pointer as a previously deleted pointer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
int main ()
{
short* short_ptr = new short{12};
std::cout << short_ptr << ",\t" << *short_ptr << "\n\n";
delete short_ptr;
long* long_ptr = new long{123456};
std::cout << long_ptr << ",\t" << *long_ptr << "\n";
}
|
006E2C28, 12
006E2BF8, 123456 |
If you are lucky trying to access a deleted pointer, read or write, will crash the program immediately. Corrupting memory while continuing to run, as TDM GCC does, is hard to debug.