从std向量中的push_back()崩溃

时间:2013-10-17 13:52:56

标签: c++ vector crash push-back

此程序按预期工作:

#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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

要添加到此(因为第一个Google结果):在我的szenario中,即使我仍然有几GB可用内存,我也得到bad_alloc

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

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

由于矢量的自动调整大小如何工作,你将以~1gb / ~2gb矢量大小命中断点

相关问题