【问题标题】:'new' causes std::bad_alloc on relatively not-large allocation'new' 导致 std::bad_alloc 分配相对较小
【发布时间】:2015-11-28 04:00:48
【问题描述】:

我正在开发一个程序,用于处理接近 1:1 微米:像素比率的电路图片,因此我在各种向量中拥有相当多的元素,这些元素是动态分配的(通过constructor for CImg)。除此之外,我只分配了几个 Qt 小部件。

CImg<unsigned char> image(this->image.width(), this->image.height(), 1, 3, 0);

这就是它的原因。

CImg(const unsigned int size_x, const unsigned int size_y,
    const unsigned int size_z, const unsigned int size_c, const T& value) :
    _is_shared(false) {
    const unsigned long siz = (unsigned long)size_x*size_y*size_z*size_c;
    if (siz) {
        _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c;
        try { _data = new T[siz]; /*thrown here*/ }
        catch (...) {
            _width = _height = _depth = _spectrum = 0; _data = 0;
            throw CImgInstanceException(_cimg_instance
                "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).",
                cimg_instance,
                cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c),
                size_x, size_y, size_z, size_c);
        }
        fill(value);
    }
    else { _width = _height = _depth = _spectrum = 0; _data = 0; }
}

构造函数调用中的image.width()image.height() 分别约为25000 和900。这使得siz 接近 6600 万。因此,分配了大约 66MB 的无符号字符。

谷歌搜索给了我一堆提示内存碎片的结果。在使用高峰期,该程序使用了 2GB。当然,Windows 可以在剩余的大于 6GB 的内存中找到 66MB 的位置,这不可能是内存碎片,对吧?也就是说,还能是什么?

我要补充一点,这只会在调试模式下编译后发生,而不是在发布模式下编译后发生。

【问题讨论】:

  • 您是否在 32 位模式下运行?
  • @jdigital 我确实是。 64 位计算机上的 32 位程序。
  • 碎片更可能是 32 位应用程序可用的有限地址空间的问题。
  • @jdigital 这并没有解决它在调试和发布模式下发生的问题。
  • “在使用高峰期,该程序使用了 2GB”。这就是 Windows 中 32 位程序默认拥有的全部。其他 2GB 用于加载系统 DLL 等。您可以为程序自己的目的配置东西以获得 3GB,但我只是将其构建为 64 位程序。假设 Qt 支持。如果不支持,那么我会将 GUI 和功能分开。无论如何,这是个好主意。

标签: c++ windows memory-management visual-studio-2015 allocation


【解决方案1】:

已修复。需要 /LARGEADDRESSAWARE 来解决 32 位内存限制。

谢谢@jdigital。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    相关资源
    最近更新 更多