I'm playing a little with memory dynamic allocation, but I don't get a point. When allocating some memory with the new
statement, I'm supposed to be able to destroy the memory the pointer points to using delete
.
But when I try, this delete
command doesn't seem to work since the space the pointer is pointing at doesn't seem to have been emptied.
Let's take this truly basic piece of code as an example:
#include <iostream>
using namespace std;
int main()
{
//I create a pointer-to-integer pTest, make it point to some new space,
// and fulfill this free space with a number;
int* pTest;
pTest = new int;
*(pTest) = 3;
cout << *(pTest) << endl;
// things are working well so far. Let's destroy this
// dynamically allocated space!
delete pTest;
//OK, now I guess the data pTest pointed to has been destroyed
cout << *(pTest) << endl; // Oh... Well, I was mistaking.
return 0;
}
Any clue ?
delete
will do is allow that memory to be allocated to something else. It may or may not change the values stored in the actual bits. But reading those bits using a pointer to the deleted object causes undefined behavior – Superstition