简体   繁体   English

数组C语言中的堆栈和缓冲区溢出

[英]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,, 好吧,我是C语言编程的新手,并且不熟悉缓冲区和堆栈的主题..任何人都可以找出问题的原因..谢谢,

here's my program..first i am getting a runtime error 这是我的程序..首先我遇到运行时错误

"Stack around the variable 'arr2' was corrupted" “变量'arr2'周围的堆栈已损坏”

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) “ arr2.exe中发生了缓冲区溢出,这已破坏了程序的内部状态。按Break调试程序或继续终止程序。”(arr2是我的程序名)

this is my source code (microsoft visual studio 2010)(c language)this program is just meant read the the elements of two arrays 这是我的源代码(Microsoft Visual Studio 2010)(C语言),该程序仅用于读取两个数组的元素

#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 . 在C中,数组从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循环会导致您出错:

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

You'll try accessing arr1[i][2] which is not defined (also for i >= 2). 您将尝试访问未定义的arr1[i][2] (也适用于i> = 2)。 Since you declared your array like this form : int arr[2][2] , you will need this for-loop instead : 由于您使用以下形式声明了数组: int arr[2][2] ,因此需要此for循环:

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). 您所有的for循环可能都不正确(因为声明t[2]数组时索引应为0或1)。 The <= should be < like eg <=应该是< ,例如

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

and please learn how to use the debugger . 并且请学习如何 使用调试器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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