2016-03-30 5 views
0

もう一度Cを使い始めました。 似たような質問がたくさんありますが、答えはここにあります。 誰かが私が間違ったことを教えてくれることを願っています。ランタイムチェック失敗#2:変数 'power'の周りのスタックが壊れていた

プラットフォームはWindowsですが、OSコース用ですので、XV6(Unixバージョン6の簡略版)でも動作するはずです。

私は2つの構造体があります。

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

を、私はグローバル変数を持っている:私はreturn文で次のような方法を、デバッグする場合

struct item* polynom1; 

私は例外「ランタイムチェックを取得失敗番号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(enter)4 4 (入力)0 0(入力)。 重要 - 'res'は正しい値を取得します。

%huを%hhu /%uに置き換えようとしましたが、同じ結果が得られました。 また、「free(nextPoly);」を追加しようとしました。 before "nextPoly = NULL;" - まだ同じ。

ありがとうございます! :)

+0

プラットフォーム....... – pm100

+7

シンプル:? 'power'は'符号なしchar'と '%のhu'ある' scanf関数に指示します'それは' unsigned short'です。 – immibis

+0

このコメントを実際の投稿にも追加します。プラットフォームはWindowsですが、それはOSコース用ですので、XV6(Unixバージョン6の簡略版)でも動作するはずです。私は%hhuと%uを試しましたが、私は同じ結果を得ました。 –

答えて

0

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

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

を交換し

関連する問題