(C++) 在抛出 'std::bad_alloc' 实例后终止调用

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

本文关键字:alloc 实例 调用 终止 bad C++ std      更新时间:2023-10-16

我一直得到内存分配不良的错误。我花了一整晚的时间想找出我哪里出了问题,但就是不知道是哪里。

我已经把每一行都梳理过了,但还是一无所获。会不会是我的程序/笔记本不够强大?

任何帮助都会非常有帮助。我的头嗡嗡作响,我需要休息。下面是我的代码:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
// struct to store word + count combinations
struct wordItem{
    string word;
    int count;
};
void getStopWords(char *ignoreWordFileName, vector<string>& _vecIgnoreWords);
bool isCommonWord(string word, vector<string>& _vecIgnoreWords);
void printTopN(wordItem wordItemList[], int topN);
void doubleArray(wordItem wordItemList[], int size);
int getTotalNumberNonCommonWords(wordItem wordItemList[], int size, int wordCount);
const int STOPWORD_LIST_SIZE = 50;
// ./a.out 10 HW1-HungerGames_edit.txt HW1-ignoreWords.txt
int main(int argc, char* argv[]){
    vector<string> vecIgnoreWords(STOPWORD_LIST_SIZE);
    // verify we have the correct # of parameters, else throw error msg & return
    if (argc != 4){
        cout << "Usage: ";
        cout << argv[0] << " <number of words> <filename.txt> <ignorefilename.txt>"<< endl;
        return 0;
    }
    //Set vector with stop words
    getStopWords(argv[3], vecIgnoreWords);
    //initialize struct array
    int aSize = 100;
    wordItem *theStructArray = new wordItem[aSize];
    int counter = 0;
    int doubleCount = 0;
    //read main txt file
    ifstream inFile(argv[1]);
    if(inFile.is_open()){
        string line;
        string theWord;
       //extract words from file
        while(getline(inFile, line)){
            istringstream iss(line);
            //extract and analyze word
            while(iss >> theWord){
                if(!(isCommonWord(theWord, vecIgnoreWords))){
                    bool inStructArray = false;
                    int inStructPosition;
                    //search for word in Struct array
                    while (inStructArray == false){
                        for(int i=0; i<aSize; i++){
                            if (theWord == theStructArray[i].word){
                                inStructArray = true;
                                inStructPosition = i;
                            }
                        }
                        break;
                    }
                    //if word is in struct array
                    if (inStructArray == true){
                        theStructArray[inStructPosition].count++;
                    }
                    //else if it isn't
                    else{
                        //create new wordItem and add into struct                           
                        wordItem newWord;
                        newWord.word = theWord;
                        newWord.count = 1;
                        theStructArray[counter+(100*doubleCount)] = newWord;
                        counter++;
                    }
                    //if struct array hits maximum amount of elements,
                    if (counter == (aSize-1)){
                        doubleArray(theStructArray, aSize);
                        counter = 0;
                        doubleCount++;
                        aSize +=100;
                    }
                }
            }   
        }
        inFile.close();
    }
    //Bubble sort masterArray
    int bI, bJ, flag = 1;
    wordItem bTemp;
    for(bI=1; (bI <= aSize && flag); bI++){
        flag = 0;
        for(bJ=0; bJ<aSize; bJ++){
            if(theStructArray[bJ+1].count > theStructArray[bJ].count){
                bTemp = theStructArray[bJ];
                theStructArray[bJ] = theStructArray[bJ+1];
                theStructArray[bJ+1] = bTemp;
                flag = 1;   
            }
        }
    }
    //Print topN words
    printTopN(theStructArray, atoi(argv[1]));
    //print others
    cout << "#" << endl;
    cout << "Array doubled: " << doubleCount << endl;
    cout <<"#" << endl;
    cout << "Unique non-common words: "<< (aSize-100+counter)<<endl;
    cout << "#"<<endl;
    cout <<"Total non-common words: "<< getTotalNumberNonCommonWords(theStructArray, aSize, counter)<<endl;
    return 0;
}
void getStopWords(char *ignoreWordFileName, vector<string>& _vecIgnoreWords){
    ifstream inFile(ignoreWordFileName);
    if(inFile.is_open()){
        int a = 0;
        string line;
        while(getline(inFile, line)){
            _vecIgnoreWords.insert(_vecIgnoreWords.begin() + a, line);
        }
        inFile.close();
    }
    return;
}
bool isCommonWord(string word, vector<string>& _vecIgnoreWords){
    for(int i=0; i<STOPWORD_LIST_SIZE; i++){
        if(word == _vecIgnoreWords.at(i)){
            return true;
        }
    }
    return false;
}
void printTopN(wordItem wordItemList[], int topN){
    cout << endl;
    for(int i=0; i<topN; i++){
        cout<< wordItemList[i].count << '-' << wordItemList[i].word << endl;
    }
    return;
}
void doubleArray(wordItem wordItemList[], int size){
    wordItem *tempArray = new wordItem[size+100];
    for(int i=0; i<size; i++){
        tempArray[i] = wordItemList[i];
    }
    delete [] wordItemList;
    wordItemList = tempArray;
}
int getTotalNumberNonCommonWords(wordItem wordItemList[], int size, int wordCount){
    int total = 0;
    for(int i=0; i<(size-100+wordCount); i++){
        total+=wordItemList[i].count;
    }
    return total;
}

你在void doubleArray(wordItem wordItemList[], int size)做了非常糟糕的事情

如果您传递一个数组,您可以在数组上调用delete [],但是您不能更改它的值,因此doubleArray(theStructArray, aSize);将导致theStructArray被删除,但不会分配给您分配的内存。您只是在函数doubleArray

中分配局部变量

类似于:

void doubleit(int x)
{
   x *= 2;
}
int y=3;
doubleit(y);

这里x暂时翻倍为6,但y从未改变。

你需要使用引用,或者最好让theStructArray成为std::vector,并完成它。