Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading