c++eigen

Strange behavior of Eigen's Map


When calling a function that returns a vector inside Eigen::Map, the map results in a wrong result. But, if the vector is first allocate and the Eigen::Map is applied, the expected result is achieved. Is this a bug?

Working code

#include <Eigen/Eigen>
#include <iostream>
#include <vector>

std::vector<double> create_vector(double const a, double const b)
{
    return {a, b, a + b, a * b};
}

int main()
{
    Eigen::Map<const Eigen::Vector<double, 4>>
        eigen_vector_1(create_vector(1.0, 2.0).data());

    std::cout << eigen_vector_1 << std::endl;

    auto const vector = create_vector(1.0, 2.0);

    Eigen::Map<const Eigen::Vector<double, 4>>
        eigen_vector_2(vector.data());

    std::cout << eigen_vector_2 << std::endl;

    return 0;
}

Solution

  • The vector is returned by value which will be destroyed at the end of the full expression and create_vector(1.0, 2.0).data() uses that to-be-destroyed vector's pointer so the first leads to undefined behavior.

    This is basically a dangling pointer use issue.

    Note that clang gives warning for the same:

    <source>:12:15: warning: object backing the pointer will be destroyed at the end of the full-expression [-Wdangling-gsl]  
    

    Warning with clang