I have a class pointer declaration:
MyClass* a;
In destruction method I have:
if (a)
{
delete a;
a= NULL;
}
I got a problem when delete the pointer a:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
What is the cause of the problem and how can I get rid of it?
With your current declaration:
agets a random value. If you never give it a valid value later, such as:It will point to an unknown place in memory, quite probably not a memory area reserved for your program, and hence the error when you try to delete it.
The easiest way to avoid this problem is to give
aa value when you declare it:or, if you cannot give it a value when you declare it (maybe you don’t know it yet), assign it to null:
By the way, you can remove the test (
if (a)) from your code.deleteis a no-op on a null pointer.