gpt4 book ai didi

c - 运行时检查失败#2 : Stack around the variable 'power' was corrupted

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

我刚刚再次开始使用 c,但我不知道我在哪里破坏了堆栈。有很多类似的问题,但这里的答案是个别的。我希望有人能告诉我我做错了什么。

平台是 Windows,但它是针对操作系统类(class)的,因此它也应该适用于 XV6(Unix 版本 6 的简化版本)。

我有两个结构:

struct elem {
unsigned char power; // the power of this item
float coef; // the coefficient
};
struct item {
struct elem* elem;
struct item* next;
};

我有一个全局变量:

struct item* polynom1;

当我调试以下方法时,在 return 语句处出现异常“运行时检查失败 #2:变量“power”周围的堆栈已损坏”:

struct item* readPolynom()
{
struct item* res = (struct item*)malloc(sizeof(struct item));
struct item* nextPoly = res;
unsigned char power;
float coef;

res->next = NULL;

do
{
scanf("%hu%f", &power, &coef);

if (power != 0 || coef != 0)
{
nextPoly->elem = (struct elem*) malloc(sizeof(struct elem));
nextPoly->elem->coef = coef;
nextPoly->elem->power = power;
nextPoly->next = (struct item*) malloc(sizeof(struct item));
nextPoly = nextPoly->next;
}
} while (power != 0 || coef != 0);

nextPoly = NULL;

return res;
}

输入为:5 5.5(输入)4 4(输入)0 0(输入)。重要 - 'res' 获取正确的值。

我也尝试用 %hhu/%u 替换 %hu,但得到了相同的结果。我还尝试添加“free(nextPoly);”在“nextPoly = NULL;”之前- 还是一样。

提前致谢! :)

最佳答案

替换

scanf("%hu%f", &power, &coef);

int tmppower;
scanf("%hu%f", &tmppower, &coef);
if (tmppower > 255)
{
printf("Invalid power\n");
exit(1);
}
power = (char)tmppower;

关于c - 运行时检查失败#2 : Stack around the variable 'power' was corrupted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36320489/

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