运行时检查失败#2 - 变量'MinNum'周围的堆栈已损坏
问题描述:
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
void main()
{
unsigned _int8 MinNum;
unsigned _int8 MaxNum;
unsigned _int8 Guess;
unsigned _int8 MagicNum;
printf("Please enter the minimum value (0 - 255): ");
scanf("%d", &MinNum);
printf("Please enter the maximum value (%d - 255): ", MinNum);
scanf("%d", &MaxNum);
printf("Guess a number between %d - %d", MinNum, MaxNum);
scanf("%d", &Guess);
srand((unsigned)time(NULL));
MagicNum = (rand() % MaxNum + MinNum);
if (Guess > MagicNum)
{
printf("You guessed too high.");
}
else if (Guess < MagicNum)
{
printf("You guessed too low.");
}
else
{
printf("You win.");
}
}
此代码给了我标题中指定的错误。我环视了一下互联网,发现这个错误是由于你分配给一个变量的数据超过了数据限制,但不知道它超出了MinNum的限制。运行时检查失败#2 - 变量'MinNum'周围的堆栈已损坏
答
scanf("%d", &num)
预计num
有int
-类型。传递sizeof(othertype) < sizeof(int)
类型的地址是未定义的行为。
如果要将scanf()
转换为char
大小的变量,则必须使用scanf("%hhd", &num)
或scanf("%c", &num)
。
顺便说一句,同样的原理适用于printf()
。当使用printf("%hhd", num)
或printf("%c", num)
时,num
的类型为char
。
另外,C中的返回类型main()
是int
。
打开编译器警告(如果已经存在的话,只需要注意它们)。他们会让问题变得明显。 – 2014-10-16 21:35:08