Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak in class Constructor of c++

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 ?

like image 994
user3863252 Avatar asked Jul 22 '14 05:07

user3863252


People also ask

How are memory leaks caused in C?

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.

How can you prevent memory leak in C which?

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.

What is memory leak with example?

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.

What is memory leak in C why it should be avoided?

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.


1 Answers

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.

like image 193
jxh Avatar answered Oct 11 '22 00:10

jxh