Search code examples
c++pointerseigen3

Eigen MatrixXd pointer passed as argument to a function causes segmentation faults


The Eigen library has limitations with passing non-const Eigen variables as parameters to functions due so some issues with temporary object creation. However, they have provided several solutions and work arounds mentioned here suggesting usage of the Ref templated class or passing const parameters and them casting away their constant-ness in the function.

However, they don't mention any limitations with passing Eigen matrices as pointers to functions.

void function(const int a, Eigen::MatrixXd* mat) {
   Eigen::MatrixXd temp_mat = Eigen::Matrix::Constant(2, 2, a);
   (*mat).topLeftCorner << temp_mat; 
}

Eigen::MatrixXd mat = Eigen::MatrixXd::Zero(5,5);
function(9, &mat);           // Seg Fault

I am not sure why do I get a segmentation fault in this code snippet.


Solution

  • void foo(const int a, Eigen::MatrixXd* mat)
    {
        Eigen::MatrixXd temp_mat = Eigen::MatrixXd::Constant(2, 2, a);
        (*mat).topLeftCorner(2, 2) << temp_mat;
    }
    
    
    int main()
    {
        Eigen::MatrixXd mat = Eigen::MatrixXd::Zero(5, 5);
        foo(9, &mat); 
        cout << mat;
    }
    

    works fine for me.