ailFreeing memory
-
This may be a general doubt but I do need clarification . I have declared a userdefined class object m_pElement as a member of CMainFrame. I want to release its memory in the destructor in the foll.manner. CMainFrame::~CMainFrame() { if (m_pElement) delete m_Element; } But if I had not declared memory for pElement using 'new' the above destruction leads to exception. How to check for allocated memory and then release the memory for pElement. laiju
-
This may be a general doubt but I do need clarification . I have declared a userdefined class object m_pElement as a member of CMainFrame. I want to release its memory in the destructor in the foll.manner. CMainFrame::~CMainFrame() { if (m_pElement) delete m_Element; } But if I had not declared memory for pElement using 'new' the above destruction leads to exception. How to check for allocated memory and then release the memory for pElement. laiju
In the class constructor of CMainFrame, set pointer to NULL:
CMainFrame::CMainFrame() { m_pElement = NULL; }
Like that, in your destructor, if the pointer is NULL, it won't be destroyed. -
This may be a general doubt but I do need clarification . I have declared a userdefined class object m_pElement as a member of CMainFrame. I want to release its memory in the destructor in the foll.manner. CMainFrame::~CMainFrame() { if (m_pElement) delete m_Element; } But if I had not declared memory for pElement using 'new' the above destruction leads to exception. How to check for allocated memory and then release the memory for pElement. laiju
Set m_pElement to NULL in your constructor. Then, the if statement will actually work and the delete will not be executed. And even if it is, it's not a problem to delete a pointer to NULL. In your case however, m_pElement can point to 0x0ccccc (arbitrary) and you're trying to delete it which is not legal.