简体   繁体   中英

pointer being freed was not allocated after removing a string

I'm trying to remove a specific word from a text file and then rewrite the remaining values into a new file. I believe that the error arises from the code here:

string removeWord(string r){
    ifstream wordBase("WordDatabase.txt");
    ofstream temp("temp.txt");

    string line = "";
    while(getline(wordBase,line))
    {
        if(line != r)
            temp << line << endl;
    }

    temp.close();
    wordBase.close();
    remove("WordDatabase.txt");
    rename("temp.txt","WordDatabase.txt");
}

Can someon help me out here? Highly appreciated!

The code has undefined behaviour as (pointed out by John Sheridan ) the function removeWord() is not return ing a string but a string as its return type. From section 6.6.3 The return statement of the c++11 standard (draft n3337), clause 2:

...Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

It is pointless trying to reason about the behaviour of a program that has undefined behaviour but given there is an error in the code related to a string and string is mentioned in the error message this is a probable cause. To correct, change the return type to void or return a string .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM