I have the following class
class CSample
{
char* m_pChar;
double* m_pDouble;
CSample():m_pChar(new char[1000]), m_pDouble(new Double[1000000])
{
}
~CSample()
{
if(m_pChar != NULL) delete [] m_pchar;
if(m_pDouble != NULL) delete [] m_pDouble;
}
};
and in my main() function i'm trying to create object of CSample
int main()
{
try
{
CSample objSample;
}
catch(std::bad_alloc)
{
cout<<"Exception is caught !!! Failed to create object";
}
}
Say while allocating the memory for m_pDouble in constructor's initializer list, it throws the exception because of insufficient available memory. But for m_pChar it is already allocated. Since object itself is not created, the destructor wouldnt be called. Then there will be memory leak for m_pChar.
How do you avoid this memory leak ?