Error! Why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <conio.h>
#include <string>
#include <iomanip>

using namespace std;

int main()
{
	
	int a[10][10];

	for(int i=0; i<=10; i++)
		for(int i2=0; i2<=10; i2++)
			a[i][i2]=i*i2;

	for(int i=0; i<=10; i++)
	{
		for(int i2=0; i2<=10; i2++)
		cout<<setw(3)<<a[i][i2]<<" ";
		cout<<endl;
	}



	getche();

	return 0;
}



ERROR:

Run-Time Check Failure #2 - Stack around the variable 'a' was corrupted.
Your code is correct and it works fine with me. You may want to compile it again and try again. Your code has zero errors while working in Borland.
I working with MS Visual Studio 2010 Ultimate.
You should try to compile it with a GNU GCC compiler and when you do that, drop the conio.h header and the getche() function. That code compiles with succes in Code::Blocks with the compiler named above. That error refers to an inability of accesing the stack memory when the a - variable has to use it. That error might signaling a system issue.
There are definitely errors in your code.

1
2
3
4
5
	int a[10][10];

	for(int i=0; i<=10; i++)
		for(int i2=0; i2<=10; i2++)
			a[i][i2]=i*i2;


If you have an array of size [10], this means that array indexes of [0] through [9] are valid. Index [10] is out of bounds and cannot be accessed.

In this loop, you are accessing up to [10][10], when the upper bound of your a array is [9][9], so you are out of bounds. hence the stack corruption and runtime error.

Either up the array size to [11][11], or change your loops to use < instead of <=
Disch "i<=10;" this means less than or equal to 10. 9 is infact less than 9 therefore this code works fine. I have just run this code on my compiler using BORLAND and it gives me zero erros and the output is fine.
Disch is correct.

i <= 10 includes the values 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, AND 10. The 10 value is out of bounds and invalid. That's why the program is in fact incorrect.

Why the program works for you in BORLAND is just a lucky happenstance of Borland's compilers. The program is writing to memory outside of the 2-D array, and happened to not cause irrecoverable problems. However, in another system it did.

The fact that the program works for you is not evidence that it is correct.
Disch "i<=10;" this means less than or equal to 10


Yes. Since i starts at 0, this gives you a range [0..10] which is 11 iterations, not 10.

"i < 10" would give you [0..10) or [0..9], which is the desired 10 iterations.

You do not want to include 10 in your range here.

9 is infact less than 9 therefore this code works fine. I have just run this code on my compiler using BORLAND and it gives me zero erros and the output is fine.


If you look at the output in more detail, you might notice it's proving me right. The output here will be producing an 11x11 table, not a 10x10 one.


EDIT: doh Doug already replied
Last edited on
Topic archived. No new replies allowed.