smalltock
smalltock

Reputation: 5

std::out_of_range error accessing a std::string in C++

I am part of a team of three moderate-aptitude programmers, and we are currently attempting to write a program in C++ to embody our new encryption algorithm. However, we have encountered an error which indicates that we are surpassing the length of a string, at some point. I have tried debugging this, myself, but I have had no luck. It's in the jumble() function, though ...

Anyway, here's a paste of our sourcecode with a temporary main() function: http://pastebin.com/GvvYAsKg

It compiles fine, but upon running, we get the following error:

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

Upvotes: 0

Views: 245

Answers (2)

john
john

Reputation: 87959

Presumably this piece of code

if(modCount >= inPT.length())
{
    modCount = 0;
}
int mod = inKey.at(modCount);         

is meant to read

if(modCount >= inKey.length())
{
    modCount = 0;
}
int mod = inKey.at(modCount);         

Your guard on an out of range access on inKey is using the wrong variable.

Upvotes: 7

Philip Kendall
Philip Kendall

Reputation: 4314

One of your problems is in this line:

for(int i = 0; i < ( inPT.length() + 1 ); i++)

This will mean you attempt to access inPT[inPT.length] which is one character beyond the end of the string. You want

for(int i = 0; i < inPT.length(); i++)

or possibly to be using a more idiomatic C++ construct like std::for_each so you can't make this kind of fencepost error. As noted in the comments, running this in a debugger would have pointed this out to you pretty quickly.

Upvotes: 7

Related Questions