'new' 在相对较小的分配上导致 std::bad_alloc

'new' causes std::bad_alloc on relatively not-large allocation

我正在开发一个用于处理接近 1:1 micrometer:pixel 比率的电路图片的程序,因此我在各种动态分配的向量中有相当多的元素(通过 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 的位置,这不会是内存碎片,对吧?也就是说,它还能是什么?

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

已修复。需要 /LARGEADDRESSAWARE 来对抗 32 位内存限制。

谢谢@jdigital。