简体   繁体   中英

std::out_of_range error?

I'm dealing with a file with a linked list of lines with each node looking like this:

struct TextLine{
    //The actual text
    string text;
    //The line number of the document
    int line_num;
    //A pointer to the next line
    TextLine * next;
};

and I'm writing a function that adds spaces at the beginning of the lines found in the variable text , by calling functions like linelist_ptr->text.insert(0,1,'\\t');

The program compiles, but when I run it I get this error:

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at
Aborted

Any ideas?

You are using the std::string::at() somewhere in your code but you are passing it an incorrect index, hence it throws. Since you don't catch any exceptions it propagates out of main() and terminate() is called, killing the process.

The code you've shown can't fail in that way, as std::string::insert() doesn't call std::string::at(), nor are the parameters. Please add exception handling to your code and if you still can't find the bug please post a larger section of your code (or the whole file, to http://codepad.org preferably).

I think the most likely problem from what you've described is that insert() is being invoked with an invalid position off the end of the string (ie > size()). You say this example is like the functions you're calling, so check the ones you may have written where you might be passing position differently than the sample code above and make sure the value is what you expect.

The terminate message is because you're not handling the out_of_range exception (via try/catch blocks), so it escapes up to the C++ language runtime, which unceremoniously shuts your program down.

检查linelist_ptr是否具有合法值,即是否已对其进行了new编辑(并且在使用前未将其delete

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