Search code examples
pointersvisual-c++nulldelete-operator

Class objects destruction


In the following code I intentionally set a pointer, p, to NULL after deleting it so that the second object can't delete it again. However, I recieve the following error dialog in Microsoft Visual C++: Debug Assertion Failed - Expression: _BLOCK_TYPE_IS_VALID(pHead -> nBlockUse)

Full size image of the error dialog.

#include <iostream>
#include <string>
using namespace std;

class line{
public:
    line();
    ~line();
    int* p;
};

line::line(){
    p = new int;

}

line::~line()
{
    if (p != NULL)
    {
        delete p;
        p = NULL;
    }
}


int main()
{
    line line1,
        line2 = line1;
    cout << line1.p << endl << line2.p;

    cin.get();
    return 0;
}

Solution

  • line1 and line2 are both holding a pointer.

    You need to understand that line1.p is a separate variable toline2.p, even though they are pointing to the same address in memory.

    Suppose that the line2 destructor is invoked first. It will set line2.p to NULL, but this will not alter the location that line1.p is pointing to.

    When the line1 destructor is subsequently invoked, it will attempt to deallocate the already deallocated data that line1.p is pointing to, hence the Debug Assertion.