Search code examples
c++memoryeigen

When does Eigen matrix release heap memory?


I would like to write a very very tiny matrix/tensor library with minimal features, and API like Eigen.

What confused me is, setting a debug break point, does not take me into some destructor function, I get nothing.

To reproduce, use this snippet that uses Eigen:

#include <Eigen/Dense>
#include <stdio.h>
#include <iostream>
using namespace Eigen;

int main()
{
    printf("hello Eigen\n");
    {
        MatrixXf m1(300, 400);
        MatrixXf m2(300, 400);
        MatrixXf m3 = m1 + m2;
        std::cout << m3.rows() << std::endl;
        printf("bye\n"); 
    }  // set a debug break point in this line, expecting going into its destructor and free memory, but there isn't
    printf("-----------------\n");

    return 0;
}

As a comparison, I simple created a Tensor template class, and when leaving its scope, its destructor is called:


template<class T>
class Tensor {
public:
    int c, h, w;
    int len;
    T* data;
    Tensor(int _c, int _h, int _w): c(_c), h(_h), w(_w) {
        len = c * h * w;
        data = new T[len];
    }
    ~Tensor() {
        if (data) {
            free(data);
        }
    }
};


int main() {

    // Tensor
    {
        printf("hello tensor\n");
        Tensor<float> tensor(3, 2, 2);
        printf("bye tensor\n");
    } // set a debug break point here, Tensor class's destructor is called
    
    return 0;
}

My question: when and where does Eigen's big matrix (with heap memory allocated) free its heap memory? And how can I see that?


update: I forget to mention that I was using Visual Studio 2019 Debug mode.


Solution

  • This is the compiler and debugger difference, after tried difference tools and methods from comments in this problem description.

    The Visual Studio 2019 (until 2021-4-9, version 16.9.3) still can't debug step into DenseStorage class's destruction function.

    While, Visual Studio 2019 with clang-cl, and lldb/gdb with clang-10/g++-9.3 on Linux, all can debug into DenseStorage class's destruction function.