运行时检查失败#2:堆叠变量' power'已损坏

时间:2016-03-30 21:58:59

标签: c

我刚开始再次使用c而且我无法弄清楚我在哪里压缩堆栈。 有很多类似的问题,但答案是个人在这里。 我希望有人可以告诉我我做错了什么。

该平台是Windows,但它适用于OS课程,所以它应该适用于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;" - 还是一样。

提前谢谢! :)

1 个答案:

答案 0 :(得分:1)

替换

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

通过

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