Skip to content

Eigen::SparseMatrix<float>::setFromTriplets return segmentation fault

overview

when the tripletList.size() is bigger than INT_MAX + 1, the A.setFromTriplets(tripletList.begin(), tripletList.end()); will return “ Segmentation fault(core dumped) ”

detail

hello, I try to set a sparse matrix A with setFromTriplets, my cpp code as below

#include <iostream>
#include <vector>
#include <string>
#include <Eigen/Sparse>
#include <Eigen/Dense>
#include <Eigen/SVD>
#include <Eigen/Sparse>
#include <climits>

int main(int argc, char const *argv[])
{
    // INT_MAX = 2147483647
    // unsigned idx = 2147483648;  // run successfully
    unsigned idx = 2147483649;  // segmentation fault
    
    std::vector<Eigen::Triplet<float>> tripletList;
    tripletList.resize(idx);
    std::cout << "tripletList.size() is " << tripletList.size() << std::endl;
    for (unsigned i = 0; i < idx; i++)
    {
        tripletList[i] = (Eigen::Triplet<float>(i%20, i%20, 0.000005));
    }
    std::cout << "tripletList is done ." << std::endl;
    Eigen::SparseMatrix<float> A;
    A.resize(20, 20);
    A.setZero();
    A.setFromTriplets(tripletList.begin(), tripletList.end());
    std::cout << "setFromTriplets is done !" << std::endl;
    return 0;
}

the problem is :

when the tripletList.size() is bigger than INT_MAX + 1 (on my x64 ubuntu20.04,the INT_MAX is 2147483647),the A.setFromTriplets(tripletList.begin(), tripletList.end()); returns "Segmentation fault(core dumped)" ;

but when the tripletList.size() <= INT_MAX + 1 , the program runs successfully.

I want to confirm if this is a bug or just a feature, I haven't found the explanation in the official reference about setFromTriplets() .

thank you.