gpt4 book ai didi

c - 在 Visual Studio 2013 中, "Run-Time Check Failure #2 - Stack around the variable ' b' 已损坏。”

转载 作者:行者123 更新时间:2023-11-30 15:20:05 25 4
gpt4 key购买 nike

首先,我要感谢您调查我的问题。

自从我开始使用 C 编码以来,我一直使用代码块进行编码,最近我不得不改用 Visual Studio 来完成我的大学实验室作业。本周我们的作业非常简单,但我似乎一直遇到这个错误,该错误仅在使用 Visual Studio 时出现,而在任何其他 IDE 中都不会出现。我想知道是否有人可以帮助我解决这个问题,并告诉我我做错了什么?我将在下面附上我的代码。

非常感谢!

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<time.h>
void main()
{
srand(time(NULL));
int a, n;
char b ='y';
while (b == 'y')
{
n = rand() % 3000 + 1; // 1-3000


puts("I have generated a number between 1 and 3000. Can you guess mynumber?\nPlease type your first guess (0-3000):");
scanf("%d", &a);

while (a != n)
{
if (a > n)
printf("Too high. Please try again.\n");
if (a < n)
printf("Too low. Please try again.\n");
scanf("%d", &a);
}
printf("Excellent! You guessed the number!\n");
printf("Would you like to play again? (y or n)\n");
scanf("%s", &b);
}
printf("Have a nice day.\n");
system("PAUSE");
}

此代码旨在生成 1-3000 之间的随机数,并让用户猜测。然后用户可以选择是否再次玩。当用户键入“n”结束外部 while 循环时,会发生错误。

再次感谢!

最佳答案

注意 scanf 的危险:

scanf("%s", &b);

b 是一个 char,但您为 scanf 提供了 %s 的说明符。 %s 说明符用于字符缓冲区,而不是单个字符。发生的情况是 scanf 假设 b 是指向缓冲区的指针,因此您会覆盖内存。

您应该指定%c,因为这是单个字符的说明符。

此外,仅仅因为您在 Codeblocks 中没有看到这一点(可能使用 gcc)并不意味着程序没问题,而只是 Visual Studio 有问题。程序错误,您观察到的是未定义的行为。当您覆盖内存时,任何事情都可能发生,包括“工作正常”。

关于c - 在 Visual Studio 2013 中, "Run-Time Check Failure #2 - Stack around the variable ' b' 已损坏。”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30203923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com