Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix/correctly initialise/clean up matrix class leaking memory

The following example code using the SmallMatrix-class from SG2 package seems to cause a memory leak. In this simplified example only little memory is leaked. But my more involved algorithm tends to run out of memory.

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

See the Valgrind 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 relevant constructor is the 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 a listing 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;};

This seems fine to me. Is it? Is memory really leaked? How to fix it? Am I maybe declaring or initialising incorrectly?

like image 395
cOlumbiA Avatar asked May 19 '26 15:05

cOlumbiA


1 Answers

You are both using the initialization list and an explicit initialization.

The constructor of small_matrix calls init() with the array you created in the initialization list. Then you manually call init() that replaces the pointer to the array. So you loose 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);
}

Should fix the memory leak

like image 107
B3rn475 Avatar answered May 22 '26 07:05

B3rn475