c++ - 使用 bad_alloc 处理大 vector 会使程序崩溃

标签 c++

我有一个很大的vector<string>我需要处理的(大约 100 万个大小):

stringstream numStr;
cout << "before loop" << endl;
for(unsigned int i = 0; i < numList.size(); i++) {
    cout << i << ": " << ((NORM_MAX - NORM_MIN) * (atoi(numList[i].c_str()) - min)) / (max - min) + NORM_MIN << endl;
    int number = ((NORM_MAX - NORM_MIN) * (atoi(numList[i].c_str()) - min)) / (max - min) + NORM_MIN;
    numStr << number;
    numList[i] = numStr.str();
}

但是,程序在到达 36691 ~ 36693 时崩溃

(snip)  
36689: 288  
36690: 264  
36691: 245  

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc

我该怎么做才能找出这个问题的原因?

最佳答案

就目前的代码而言,您拥有 stringstream 在循环之外,这意味着您不断地将新数字一遍又一遍地附加到现有流的末尾,然后在每次循环迭代中存储ENTIRE LIST:

numList[i]   = "... 288"
numList[i+1] = "... 288 264"
numList[i+2] = "... 288 264 245"

等等……

所以是的,这将最终在尝试分配单个时耗尽内存string如果 numList.size(),则其中包含格式化的完整列表非常大。

您可能打算将 stringstream 在循环内,以便每次迭代格式化并存储一个单个 int每个值 numList插槽:

cout << "before loop" << endl;
for(unsigned int i = 0; i < numList.size(); i++) {
    int number = ((NORM_MAX - NORM_MIN) * (atoi(numList[i].c_str()) - min)) / (max - min) + NORM_MIN;
    cout << i << ": " << number << endl;
    stringstream numStr;
    numStr << number;
    numList[i] = numStr.str();
}

numList[i]   = "288"
numList[i+1] = "264"
numList[i+2] = "245"

等等……

关于c++ - 使用 bad_alloc 处理大 vector 会使程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28933604/

相关文章:

c++ - 为 Raspberry Pi 交叉编译 rethinkdb

c# - Delphi7中使用的C++ DLL函数

c++ - QT creator - 'QGraphicsScene' 没有命名类型

c++ - QSharedData 和继承

c++ - 在 C++ 中使用友元类还是为单元测试添加访问器?

c++ - 如何检测在 C++ 中通过省略号传递的参数的大小?

c++ - 以下两个涉及 map 的表达式是否等效

c++ - 对象在删除后工作

c++ - IOCTL_DISK_GET_DRIVE_LAYOUT_EX 工作不正常

C# 可能不是安全应用程序的最佳选择?