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 ?
In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.
The only way to avoid memory leak is to manually free() all the memory allocated by you in the during the lifetime of your code. You can use tools such as valgrind to check for memory leaks. It will show all the memory that are not freed on termination of the program.
An example of memory leakThe memory leak would occur if the floor number requested is the same floor that the elevator is on; the condition for releasing the memory would be skipped. Each time this case occurs, more memory is leaked.
Memory leak occurs when programmers create a memory in heap and forget to delete it. The consequences of memory leak is that it reduces the performance of the computer by reducing the amount of available memory.
You can easily avoid this kind of problem by using a vector
instead.
class CSample
{
std::vector<char> m_pChar;
std::vector<double> m_pDouble;
CSample():m_pChar(1000), m_pDouble(1000000)
{
}
};
Generally speaking, you should aim to write classes that do not require a destructor. This makes them trivially obey the Rule of Three.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With