Why doesn't delete destroy anything?

Viewed 9603

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 ?

9 Answers

Calling delete for a pointer marks the memory block pointed by it to 'free memory'. It doesn't destroy the items in the memory right away. The 'items' get destroyed only after the process has returned given that 'delete' was used for the pointer pointing to that memory block. In case 'delete' isn't used, it stays there forever resulting in a memory leak.

To solve your problem, just:

delete pTest;
pTest=NULL;
Related