0

Here is my simple program. I run it many times. Sometimes it will pop out a warning and break Turbo C. Why? I am using 32bit Windows 7.

#include <stdio.h>
#include <conio.h>

void main(){
int arr[10][10];
int i,j;
clrscr();
    for(i=1;i<11;i++){
        for(j=1;j<11;j++){
        arr[i][j]=i*j;
        printf("%d\t",arr[i][j]);
        }
        printf("\n");
    }
}
Chad
  • 1,531
  • 3
  • 20
  • 46
Lai Louis
  • 1
  • 1
  • 1
    Read http://stackoverflow.com/questions/7320686/why-does-the-indexing-start-with-zero-in-c – cadaniluk May 15 '15 at 17:33
  • that's why one should also run a static analyzer over c code, e.g., http://gimpel-online.com//cgi-bin/genPage.py?srcFile=diy.c&cgiScript=analyseCode.py&title=Do-It-Yourself+Example+%28C%29&intro=This+example+allows+you+to+specify+your+own+C+code.&compilerOption=online32.lnt&includeOption={{quotedIncludeOption}}, complains – Giorgi Moniava May 15 '15 at 17:37
  • It's not crashing for "undefined reason". It's crashing because you specifically told it to access memory that wasn't yours. C arrays are indexed from 0, not 1. – Lee Daniel Crocker May 15 '15 at 19:31

2 Answers2

1

It's very simple, the reason is that arrays in c are indexed from 0 to N - 1.

So instead of

for (i = 1 ; i < 11 ; ++i)

it has to be

for (i = 0 ; i < 10 ; ++i)

because N in your case is 10, and the same for j of course.

As you can see it's not Undefined Reason, it certainly is undefined behavior, but the reason is a bug in your code, so always blame your code first, it has the highest probability to be the responsible for the unexpected behavior, if you prove that your code works and I mean a mathematical proof kind of proof, then you can blame the compiler or anyone you like.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
1

In this line:

arr[i][j]=i*j;

i and j values will range from 1 to 10. However, ar[10][10] is actually out of bounds of array.

Since C follows 0-based indexing, change this:

for(i=1;i<11;i++){
    for(j=1;j<11;j++){

to this:

for(i=0;i<10;i++){
    for(j=0;j<10;j++){
Ayushi Jha
  • 4,003
  • 3
  • 26
  • 43