I'm studying for an exam and this is on my practice test. The question is "Which type of error does the following code fragment cause?"
I was pretty sure there would be no errors, but I also can't get it to compile in VS13, I get the error:
Run-Time Check Failure #2 - Stack around the variable 'foo' was corrupted.
const int MAX = 500;
int main(void)
{
int foo[MAX];
for (int i = 0; i <= MAX; i++)
{
foo[i] = i * 2;
cout << foo[i] << endl;
}
cout << "Press any key to exit." << endl;
cin.ignore(2);
return 0;
}
Valid indexes for foo
are from 0
to MAX-1
inclusive. MAX
is past the end of the array.
Your loop runs up to, and including, MAX
. This writes beyond the end of the array, corrupting the stack.
Either increase the array size to MAX+1
so that MAX
is in range; or change the loop condition to i < MAX
to stop before reaching MAX
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments