1

该程序按预期工作:

#include <iostream>
#include <string>
#include <vector>    
using namespace std;

struct Thumbnail
{
    string  tag;
    string  fileName;
};

int main()
{
    {
        Thumbnail newThumbnail;
        newThumbnail.tag = "Test_tag";
        newThumbnail.fileName = "Test_filename.jpg";

        std::vector<Thumbnail> thumbnails;

        for(int i = 0; i < 10; ++i) {
            thumbnails.push_back(newThumbnail);
        }
    }
    return 0;
}

如果我在另一个项目(仍然是单线程)中复制并粘贴主代码块,在任何函数中,我会从注释行中得到这个异常// <-- crash at the 2nd loop

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc

如果我在任何 push_back 之前清除向量,一切都很好(但这当然不是所需的行为);这让我觉得这就像向量不能存储多个这样的对象。

这是代码崩溃的函数:

int ImageThumbnails::Load(const std::string &_path)
{
    QDir thumbDir(_path.c_str());

    if(!thumbDir.exists())
        return errMissingThumbPath;

    // Set a filter
    thumbDir.setFilter(QDir::Files);
    thumbDir.setNameFilters(QStringList() << "*.jpg" << "*.jpeg" << "*.png");
    thumbDir.setSorting(QDir::Name);

    // Delete previous thumbnails
    thumbnails.clear();

    Thumbnail newThumbnail;

    ///+TEST+++
    {
        Thumbnail newThumbnail;
        newThumbnail.tag = "Test_tag";
        newThumbnail.fileName = "Test_filename.jpg";

        std::vector<Thumbnail> thumbnails;

        for(int i = 0; i < 10; ++i)
        {
            TRACE << i << ": " << sizeof(newThumbnail) << "  /  " << newThumbnail.tag.size() << " / " << newThumbnail.fileName.size() << std::endl;
            //thumbnails.clear();                   // Ok with this decommented
            thumbnails.push_back(newThumbnail);     // <-- crash at the 2nd loop
        }

        exit(0);
    }
    ///+TEST+END+++
...

这是输出:

> TRACE: ImageThumbnails.cpp:134:Load  
0: 8  /  8 / 17
> TRACE: ImageThumbnails.cpp:134:Load  
1: 8  /  8 / 17
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc

为什么在两个不同的项目中,同一段代码会出现这种不同的行为?

平台:Windows 7、MinGW 4.4、GCC

4

2 回答 2

2

补充一点(因为第一个谷歌结果):在我的情况下,bad_alloc即使我还有几 GB 的 RAM 可用,我也得到了。

如果您的应用程序需要超过 2GB的内存,您必须在链接器设置中启用 /LARGEADDRESSAWARE 选项。

如果您需要超过 4GB,则必须将构建目标设置为 x64(在项目设置和构建配置中)

由于向量的自动调整大小的工作原理,您将在 ~1gb / ~2gb 向量大小处达到断点

于 2017-05-18T07:58:32.867 回答
1

如果在另一个应用程序中使用完全相同的代码时崩溃,则程序可能内存不足(std::bad_alloc 异常可能是因为这个原因)。检查您的其他应用程序正在使用多少内存。

另一件事......在使用 std::vectors 时使用 reserve() 方法,您会提前知道有多少元素将被推入向量中。看起来您正在推动完全相同的元素 10 次。为什么不使用包含默认对象参数的 resize() 方法?

于 2013-10-17T14:21:18.063 回答