C++ std::bad_alloc error with std::vector

995 views Asked by At

I understand this question has been asked before, but the answers seemed too specified towards the asker's code.

If this is considered a useless duplicate question feel free to remove it or mark it as a duplicate.

As far as I can tell, my code is correct for what I am trying to achieve, which is counting the number of occurrences of specified words in a text file. I would appreciate any help, thank you.

The Error

    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

Part of my main.cpp (Causing the problem)

    //vectors to hold words from two files
vector<string> wordlist;
vector<string> file;
vector<int> searchVec;

//while a is not an empty string
while (a != "") {

    //getNextWord() returns each word in order from a text file
    //a is a play script, b is a list of words to search for
    a = infile.getNextWord();
    b = infile2.getNextWord();

    file.push_back(a);

    //counts total words in play script
    count++;

    //increments and adds each word from the list of words to search for to the vector
    for (int i = 0; b != ""; i++) {

        wordlist.push_back(b);

    }

    //cycles through words to search for
    for (int j = 0; j < wordlist.size(); j++) {

        //cycle through te play script
        for (int k = 0; k < file.size(); k++) {

            //if the current play script word is the same as the test word, up the count
            if (file[k] == wordlist[j]) {

                searchCount++;

            }

        }

        //print appropriate output, re-initialise the count to 0 for the next word
        cout << "The word " << wordlist[j] << " occurs " << searchCount << " times." << endl;

        searchCount = 0;

    }

}
1

There are 1 answers

2
rockoder On BEST ANSWER

How do you think this loop terminates?:

for (int i = 0; b != ""; i++) {

    wordlist.push_back(b);

}