How to fix / properly initialize / clean up a matrix class memory leak

The following code example, using the SmallMatrix class from the SG2 package , appears to be causing a memory leak. In this simplified example, only a small amount of memory is missing. But my more involved algorithm tends to run out of memory.

#include "small_matrix.hpp"
int main() {
    SmallMatrix<double> S(1);
}

      

See Valgrind's output below.

8 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C2B800: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
   by 0x400D4A: SmallMatrix<double>::SmallMatrix(int) (small_matrix.hpp:1347)
   by 0x400C15: main (test.cpp:3)

      

The corresponding constructor is a referenced section of the source code:

template <class T>
SmallMatrix<T>::SmallMatrix(int the_m)
: small_matrix<T> (the_m, new T [the_m])
{
    T * alloced_entries;
    try
    {
        alloced_entries = new T [the_m];
    }
    catch(std::bad_alloc)
    {
        throw SMALL_MAT_NO_MEMORY;
    };
    small_matrix<T>::init (the_m, 1, alloced_entries);
}

      

Find the list of small_matrix.hpp here.

Line 1347 reads:

: small_matrix<T> (the_m, new T [the_m])

      

The destructor can be found at line 822:

~SmallMatrix () {delete [] SmallMatrix<T>::entry;};

      

It seems wonderful to me. It? Is there a memory leak? How to fix it? Perhaps I am declaring or initializing incorrectly?

+3


source to share


1 answer


You are using initialization list and explicit initialization.

The small_matrix constructor calls init () with the array created in the initialization list. Then you manually call init (), which replaces the pointer with an array. Thus, you lose the reference to the array created in the initialization list.



template <class T>
SmallMatrix<T>::SmallMatrix(int the_m)
: small_matrix<T> (the_m, NULL)
{
    T * alloced_entries;
    try
    {
       alloced_entries = new T [the_m];
    }
    catch(std::bad_alloc)
    {
        throw SMALL_MAT_NO_MEMORY;
    };
    small_matrix<T>::init (the_m, 1, alloced_entries);
}

      

Memory leak needs to be fixed

+5


source







All Articles