Formatting a string error.

Why is it that when I call this function from any other, it gives me an out_of_range at memory location foo error?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
string format(string text) // Needs lots more work, but we're getting somewhere!
{
	const int NEW_LINE = 70;
	string BREAK = "\n", DASH = "-";
	int strSize, insertBreak;

	strSize = text.size();
	insertBreak = NEW_LINE;
	while(strSize >= insertBreak)
	{
		if(isalpha(text[insertBreak]))
			text.insert(insertBreak - 1, DASH);
		text.insert(insertBreak, BREAK);
		insertBreak += NEW_LINE;
	}
	if(isalpha(text[insertBreak]))
		text.insert(insertBreak - 1, DASH);
	text.insert(insertBreak, BREAK);
	return text;
}
After the loop you know that strSize < insertBreak but you call text[insertBreak] which is likely to be out of range. I say likely because after the loop text.size() can be somewhat bigger than strSize so there is still a chance that it is inside the range.
Line 16 is the most likely culprit: You are accessing char text[insertBreak], but as a minimum, insertBreak will be 70, so for shorter-than-71-chars strings you'll be out of range for sure. Line 11 is also a potential out of range because your while uses >=. Change it to >.
Thanks so much guys! Problem solved =)
Topic archived. No new replies allowed.