【问题标题】:Too large an array of Mat objects causes Seg Fault太大的 Mat 对象数组会导致 Seg Fault
【发布时间】:2018-01-24 08:43:24
【问题描述】:
#include <iostream>
#include <opencv2/core.hpp>

int main()
{
    cv::Mat test[100000];
    std::cout << "testing" << std::endl;

    return 0;
}

返回一个段错误。我找不到有关此设置的任何信息。我想不出为什么它会弄乱内存,因为我没有用任何东西初始化垫子(因此它们都是空的,使用更多内存的 4K 图像没有问题)。

【问题讨论】:

  • 很可能是因为您无法在堆栈上挤压 100000Mat 对象。

标签: c++ arrays opencv vector segmentation-fault


【解决方案1】:

解决方案是将Mats (cv::Mat[]) 的数组转换为Mats (std::vector) 的向量。我不会假装理解为什么,但我猜向量在底层有更好的内存管理。

#include <iostream>
#include <opencv2/core.hpp>

int main()
{
    int size = 100000;
    std::vector<cv::Mat> test;
    test.resize(size);
    for(int i = 0; i < size; i++)
    {test[i] = cv::Mat::zeros(1, 256, CV_32F);}
    std::cout << "testing" << std::endl;

    return 0;
}

【讨论】:

  • 不需要size 变量或单独调整大小,只需std::vector&lt;cv::Mat&gt; test(100000); 然后使用test.size() 或迭代器或基于范围的for 循环。
  • 至于“底层内存管理”,向量分配它们的堆“数组”。本质上它在做new cv::Mat[100000]
  • @Someprogrammerdude 我故意让它比必要的更冗长,这样新程序员可能更容易理解它,但感谢您的解释 =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 2020-02-22
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多