[英]Crash from a push_back() in a std vector
该程序按预期工作:
#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
如果在另一个应用程序中使用完全相同的代码时崩溃,则可能是程序内存不足(可能是因为std :: bad_alloc异常)。 检查您的其他应用程序正在使用多少内存。
另一件事...使用std :: vectors时使用reserve()方法,您会提前知道将有多少元素被推入向量。 看来您要推完全相同的元素10次。 为什么不使用包含默认对象参数的resize()方法呢?
要添加此内容(因为第一个Google结果):在我的szenario中,即使我还有几GB的可用RAM,我也得到了bad_alloc
。
如果您的应用程序需要2GB以上的内存,则必须在链接器设置中启用/ LARGEADDRESSAWARE选项。
如果需要超过4GB ,则必须将构建目标设置为x64(在“项目设置”和“构建配置”中)
由于向量自动调整大小的工作原理,您将以〜1gb /〜2gb向量大小达到断点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.