繁体   English   中英

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

[英]stack & buffer overrun in arrays c language

好吧,我是C语言编程的新手,并且不熟悉缓冲区和堆栈的主题..任何人都可以找出问题的原因..谢谢,

这是我的程序..首先我遇到运行时错误

“变量'arr2'周围的堆栈已损坏”

然后当我推动继续时,这东西出现

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

这是我的源代码(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;
}

始终牢记索引从零开始,所以这是错误的:

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

它应该是

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

其他循环也一样。

在C中,数组从0索引。 循环

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

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

将填充通过数组。

这些for循环会导致您出错:

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

您将尝试访问未定义的arr1[i][2] (也适用于i> = 2)。 由于您使用以下形式声明了数组: int arr[2][2] ,因此需要此for循环:

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

您所有的for循环可能都不正确(因为声明t[2]数组时索引应为0或1)。 <=应该是< ,例如

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

并且请学习如何 使用调试器

暂无
暂无

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

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