处理大型向量会使用bad_alloc崩溃程序

时间:2015-03-09 00:34:06

标签: 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

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

1 个答案:

答案 0 :(得分:1)

由于您的代码现在处于正常状态,因此您在循环外部stringstream ,这意味着您不断地将新数字一遍又一遍地添加到现有流的末尾,然后在每次循环迭代中存储整个列表

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

等等......

所以,是的,最终会耗尽内存,试图分配一个 string,其整个列表如果numList.size()非常大,则在其中格式化数字。

您可能打算将stringstream 置于循环中,以便每次迭代格式化并在每个迭代中存储单个 intnumList插槽:

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"

等等......