【问题标题】:Run-Time error- Stack around the variable 'arr' was corrupted运行时错误 - 变量“arr”周围的堆栈已损坏
【发布时间】:2019-08-17 05:54:42
【问题描述】:

该程序旨在打印存储在数组中的所有输入整数。它工作正常并且打印正常,只是程序以运行时失败结束。

我试过不输入任何内容,它实际上工作正常并退出。

// Alex Ruiztagle
// 3/26/2019
// Script to do operations on user entered numbers. Also I really hate primitive types. I spend more time figuring out the right one to use than I do writing the logic.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int arr[] = {0};
    int inpt;
    int counter = 0;
    int stat = 0;
    printf("Enter some numbers \n");
    while (stat == 0) {
        scanf_s("%i", &inpt);
        if (inpt == -999 || counter == 50) {
            stat = 1;
        }
        else {
            arr[counter] = inpt;
            counter++;
        }
    }
    printf("\nYou entered \n");
    for (int i = 0; i < counter; i++) {
        printf("%i. %i\n", i + 1, arr[i]);
    }
    system("pause");
}

如果我输入 7、16、45 它应该打印出来

  1. 7
  2. 16
  3. 45

它会这样做,除非是时候终止它结束的程序 “运行时检查失败 #2 - 变量 'arr' 周围的堆栈已损坏。”

【问题讨论】:

  • 您希望arr 的大小是多少?

标签: c arrays stack


【解决方案1】:

只要counter 大于 1,代码就会出现未定义的行为,因为它正在访问数组末尾之外的 arr[]

这会导致(至少)堆栈被破坏。

因此,当程序退出时,它会在尝试返回其调用者时访问损坏的堆栈。

由于未定义的行为,任何事情都可能发生。在您的情况下,发生了段错误事件

【讨论】:

    猜你喜欢
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2012-11-08
    相关资源
    最近更新 更多