Search code examples
c++eigen

Segfault in Tranposed matrix multiplication with .eval() with Eigen 3 library


I added two .eval() just in case. I got no compilation error, and no run time warning. Just segfault.

Thanks for helping me to fix this.

Test:

#include <Eigen/Eigen>
#include <iostream>
using namespace Eigen;

int main() {
    Matrix<float, Dynamic, Dynamic> mat_b;
    Matrix<float, Dynamic, Dynamic> mat_c;

    mat_b << 1.0, 0.0, 0.5, 0.5,
             0.0, 1.0, 0.5, 0.5,
             1.0, 0.0, 1.0, 0.0,
             0.0, 1.0, 0.0, 1.0;

    mat_c << 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,
             0.0, 0.0, 0.0, 0.0, 0.0, 1.0,
             1.0, 0.0, 1.0, 0.0, 0.0, 0.0,
             1.0, 0.0, 0.0, 1.0, 0.0, 0.0;

    std::cout << (mat_b.transpose().eval() * mat_c).eval() << "\n";
}

Result:

Segmentation fault (core dumped)

Solution

  • As stated in documentatipon

    The comma initializer

    Eigen offers a comma initializer syntax which allows the user to easily set all the coefficients of a matrix, vector or array. Simply list the coefficients, starting at the top-left corner and moving from left to right and from the top to the bottom. The size of the object needs to be specified beforehand. If you list too few or too many coefficients, Eigen will complain.

    emphasis is mine. If you expect that Matrix ctor would deduce size from your formatting, that simply not possible in C++. Looks like you created 16x1 and 24x1 matrix and then try to multiply 1x16 (transposed first one) to 24x1 which is not legal.