简体   繁体   中英

stack & buffer overrun in arrays c language

well i am new bee in c programming and not familiar with the topics of buffers and stacks.. can anyone please detect the cause of the problem..thank you,,

here's my program..first i am getting a runtime error

"Stack around the variable 'arr2' was corrupted"

then when i push continue this thing appears

"A buffer overrun has occurred in arr2.exe which has corrupted the program's internal state. Press Break to debug the program or Continue to terminate the program."(arr2 is my program name)

this is my source code (microsoft visual studio 2010)(c language)this program is just meant read the the elements of two arrays

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

int main()
{
    int arr1[2][2] , arr2[2][2];
    int i,j;


    /* to read the elements of first array */
    printf("enter the elements of the first matrix\n");

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


    {
        for(j=0;j<=2;j++)
        {
            printf("enter the number[%d][%d]",i+1,j+1);
            scanf("%d",&arr1[i][j]);

        }
    }

/* to read the elements of the second array */
    printf("enter the elements of the seconf matrix\n");
        for(i=0;i<=2;i++)
        {
            for(j=0;j<=2;j++)
            {
                printf("enter number[%d][%d]",i+1,j+1);
                scanf("%d",&arr2[i][j]);
            }

        }
return 0;
}

Always keep in mind indices run from zero, so this is wrong:

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

It should be

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

Same for the other loops.

In C arrays are indexed from 0 . The loops

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

and

   for(j=0;j<=2;j++)  

will fill past the array.

These for-loop cause you the error :

for(j=0;j<=2;j++)

You'll try accessing arr1[i][2] which is not defined (also for i >= 2). Since you declared your array like this form : int arr[2][2] , you will need this for-loop instead :

for(j = 0; j < 2; j++)  // Same for i : for(i = 0; i < 2; i++)

All your for loops are probably incorrect (since when declaring a t[2] array the index should be 0 or 1). The <= should be < like eg

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

and please learn how to use the debugger .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM