【问题标题】:Run-Time Check Failure #2 - Stack around the variable 'd' was corrupted运行时检查失败 #2 - 变量 'd' 周围的堆栈已损坏
【发布时间】:2014-02-28 23:11:09
【问题描述】:

这是一个使用 C 语言制作的 FCFC 模拟器程序。我遇到了这个特定的错误“运行时检查失败 #2 - 变量 'd' 周围的堆栈已损坏。”在我完成为每个进程输入所有输入之后。 我做错了什么?

void getdata()
{   
    char d;
    printf("Enter the number of process: ");
    scanf("%d",&n);

    printf("\nDo you need to enter the arrival time of process [Y/N]: ");
    scanf("%s",&d);
    printf("\n");

    for(int i=0; i<n; i++)
    {
        printf("*******************************************\n");
        printf("Enter the %d process burst time: ",i+1);
        scanf("%d",&b[i]);
        if(d=='y' || d=='Y')
        {
                printf("Enter the %d process arrival time: ",i+1);
                scanf("%d",&a[i]);
        }
        else
        {
                a[i]=0;
        }
    }
}

【问题讨论】:

  • 重新标记为 c,不是 c++。

标签: c


【解决方案1】:

这是一个错误:

char d;
scanf("%s",&d);

因为scanf("%s") 将写入它的参数,直到它找到空格,然后附加一个空终止符。 d 只有一个字符的空间,这意味着如果至少有一个字符,那么scanf() 将写入内存,它不应该导致某种形式的损坏。使用数组并限制可读取的字符数以防止缓冲区溢出。例如:

char d[128];
scanf("%127s", d); /* One less than size to leave room for null terminator. */

检查scanf() 的返回值(以及所有返回指示失败或成功的值的函数)以确保d 已实际填充。


为了避免在scanf() 格式说明符中(基本上)重复sizeof 和数组d,这是一种维护开销并且容易出错,请构建格式说明符来读取d

char d[128];
char d_format[32];
if (snprintf(d_format, sizeof(d_format), "%%%lus", sizeof(d) - 1) > 0)
{
    if (1 == scanf(d_format, d))
    {
    }
}

使用这种方法,如果sizeof() 数组d 发生更改,则用于读取d 的格式说明符将自动更新为正确的宽度(参见演示@http://ideone.com/9IsmgH)。

【讨论】:

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