Search code examples
heap-memoryeigen3

Heap management with Eigen::Map : Is that user or Eigen::Matrix responsability?


Who does handle the heap unallocation when Eigen::Map is used with a heap memory segment to create a MAtrix ?

I couldn't find any info concerning the internal Matrix data memory segment management when Eigen::Map is invoked to build a Matrix. Here is the doc I went through : https://eigen.tuxfamily.org/dox/group__TutorialMapClass.html

Should I handle the memory segment deletion when I'am done with my Matrix "mf" in the code below ?

  int rows(3),  cols (3);
  scomplex *m1Data = new scomplex[rows*cols];
  for (int i = 0; i<cols*rows; i++)
  {  
    m1Data[i] = scomplex( i, 2*i);
  }

  Map<MatrixXcf> mf(m1Data, rows, cols);

By now, if I settle a breakpoint in the function (./Eigen/src/core/util/Memory.h) :

EIGEN_DEVICE_FUNC inline void aligned_free(void *ptr)

it's not triggered when the main exits.

May I ask you whether I should considere that I must delete the memory segment when I don't use my matrix anymore ?

Cheers

Sylvain


Solution

  • The Map object does not take ownership/responsibility of the memory that is passed to it. It could just be a view into another matrix. In that case, you definitely would not want it to release the memory.

    To quote the tutorial page you linked:

    Occasionally you may have a pre-defined array of numbers that you want to use within Eigen as a vector or matrix. While one option is to make a copy of the data, most commonly you probably want to re-use this memory as an Eigen type.

    So, bottom line, you have to delete the memory you allocated and used with the Map.