【问题标题】:Run Time Check Failure Stack around the variable was corrupted变量周围的运行时检查失败堆栈已损坏
【发布时间】:2018-05-07 15:02:29
【问题描述】:
#include <stdio.h>
main()
{
int num[9], i = 0, count = 0;

while (i<10)
{
    scanf("%d", &num[i]);

    if (num[i] % 2 == 0)
    {
        count++;
    }
    i++;
}

printf("we have %d  double numbers\n", count);
}

运行时检查失败 #2 - 变量周围的堆栈已损坏

我该怎么办?

【问题讨论】:

  • num[9] 超出数组
  • 函数必须有返回类型,特别是主函数!!
  • 那么我需要做什么你能写信给我吗?
  • while (i&lt;10) --> while (i&lt;9)
  • 每当你看到这个:运行时检查失败 #2 - 变量周围的堆栈已损坏 那么这意味着大多数时候某些数组索引超出了范围,这实际上是这里的情况(见下面的答案)。但是,当您在调试模式下编译时,此错误消息特定于 Microsoft 编译器。当数组索引超出范围时,不保证会发生

标签: c arrays loops for-loop while-loop


【解决方案1】:

可用于访问具有 N 个元素的数组的有效索引范围是 [0, N - 1] 或相同的 [0, N )。

因此while语句中的条件

while (i<10)

必须像这样重写

while (i < 9)

错误的原因是在整个程序中使用了“幻数”。 尝试使用命名常量而不是幻数,这样就很容易理解在代码的哪一部分使用了什么幻数。

程序可能看起来像

#include <stdio.h>

#define N 9

int main( void )
{
    int num[N];
    unsigned int count = 0;
    unsigned int i = 0;


    while ( i < N )
    {
        scanf( "%d", &num[i] );

        if ( num[i] % 2 == 0 ) ++count;

        i++;
    }

    printf( "we have %u  double numbers\n", count);
}

使用 for 循环代替 while 循环会更好,因为变量 i 不在循环外使用。

例如

#include <stdio.h>

#define N 9

int main( void )
{
    int num[N];
    unsigned int count = 0;

    for ( unsigned int i = 0; i < N; i++ )
    {
        scanf( "%d", &num[i] );

        if ( num[i] % 2 == 0 ) ++count;
    }

    printf( "we have %u  double numbers\n", count);
}

声明数组索引的更正确方法是使用类型size_t

其实程序中并没有用到数组。您甚至可以在不使用数组的情况下计算输入的值。

考虑到根据 C 标准,不带参数的函数 main 应声明为

int main( void )

【讨论】:

    【解决方案2】:

    您的 while 循环会命中从 0 到 9 的所有 i 值,但尝试访问 num[9] 会使您超出范围。您需要减少 while 循环范围:

    while (i<9) {
        ...
    }
    

    此外,你真的应该给你的 main() 函数一个返回类型,因为现代编译器不能容忍它丢失:

    int main()
    {
        ...
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2013-12-13
      • 2013-12-10
      • 2015-02-09
      • 2015-05-24
      • 2021-12-31
      相关资源
      最近更新 更多