当矩阵大小超过特征矩阵类型的特定限制时,c++分配错误

标签 c++ matrix eigen

在 C++ 动态库中,我使用 Eigen Library 解决了一个最小二乘问题.该 Dll 在解决问题配置的 python 软件中调用。在小型问题中,代码可以正常工作并返回正确的解决方案。如果点数增加,则库抛出 std::bad_alloc

更准确地说,最简化错误的代码是

try {
    matrixA = new Eigen::MatrixXd(sizeX,NvalidBtuple); // initialize A
    for (int i=0;i<sizeX;++i) {
        int secondIndex = 0;
        for (int k=0;k<btermSize;++k) {
            if (bterm[k] == 1) {                        // select btuple that are validated by density exclusion
                // product of terms
                (*matrixA)(i,secondIndex) = 1.0;
                secondIndex += 1;
            }
        }
    }
} catch (std::bad_alloc& e) {
    errorString = "Error 3: bad allocation in computation of coefficients!";
    std::cout<<errorString<<" "<<e.what()<<std::endl;
    return;
} catch (...) {
    errorString = "Error 4: construction of matrix A failed! Unknown error.";
    std::cout<<errorString<<std::endl;
    return;
}

其中 matrixA 在头文件中用 Eigen::MatrixXd *matrixA; 定义。

如果 sizeXNvalidBtuple 小于大约 20'000x3'000,则矩阵定义有效。如果尺寸更大,它会崩溃。

我做测试的电脑有足够的可用内存,大约15G可用内存。

这是堆/堆栈问题吗? 如何让库接受更大的矩阵?

欢迎任何评论。谢谢。

编辑: 如下面的回答所述,我不清楚 NvalidBtuple 定义:

NvalidBtuple = 0;
for (int i=0;i<btermSize;++i) {NvalidBtuple += bterm[i];}

其中 bterm 是一个 bool vector 。因此,由于在循环中我们执行检查 if (bterm[k] == 1)secondIndex 总是小于 NvalidBtuple

最佳答案

根据您问题的详细信息,矩阵需要 480Mb 的 RAM。 32 位应用程序只能访问 2Gb 的 RAM(参见例如 How much memory can a 32 bit process access on a 64 bit operating system?);分配失败,因为在应用程序的地址空间中没有可用的连续 480Mb block 。

解决该问题的最佳方法是将应用程序重新编译为 64 位。您将无法在 32 位系统中运行它,但这应该不是问题,因为由于内存有限,您无论如何都无法在这样的系统上运行您的算法。

关于当矩阵大小超过特征矩阵类型的特定限制时,c++分配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33365043/

相关文章:

c++ - C#define 嵌套在 #ifdef 中

c++ - 在 Visual Studio 中提升测试

c++ - 如何加载(mov)一个类变量到cpu寄存器

C++ 行和列矩阵操作

OpenCV Mat 每个元素操作 : vector-matrix multiplication

python - NumPy 相当于 Matlab 的 magic()

c++ - 在将 void* 转换为任何内容时,我应该使用 static_cast 还是 reinterpret_cast

c++ - 使用特征值的欧拉到四元数/四元数到欧拉

c++ - Eigen 中的点积乘以转置?

c++ - 持有多个 Eigen MatrixXd 的最有效方法