This is undefined behavior. You are accessing memory after you have deleted it.
Because deleting a block of memory does not zero the value of all pointers that point to it. Deleting memory merely makes a note that the memory is available to be allocated for some other purpose. Until that happens, the memory may appear to be intact -- but you can't count on it. And on some compiler/runtime/architecture combinations, your program will behave differently.
Two things happen when delete[]
is called:
- If the array is of a type that has a nontrivial destructor, the destructor is called for each of the elements in the array, in reverse order
- The memory occupied by the array is released
Accessing the memory that the array occupied after calling delete
results in undefined behavior (that is, anything could happen--the data might still be there, or your program might crash when you try to read it, or something else far worse might happen).
Use RAII. Either wrap it in a class or use the STL and don't manage memory yourself. C++ is powerful, but you can also blow your leg off - so to speak. A better practice would be to put it in its own scope would prevent anything beyond the scope from accessing your pointer.
{
Foo* pFoo = new Foo;
// use pFoo
delete pFoo;
}
// anything using pFoo beyond here fails at compilation