0

かなり単純なコードで奇妙な問題に直面しています。コードの関連部分を以下に示します。

void foo(int32 in_sd_id, int32 out_sd_id)
{
    int32 nsds;                     /* number of data sets in the file */
    int32 nattr;                    /* number of global attributes in the file */
    int32 attr_cnt;                 /* count of number of attribute */
    int32 attr_index;               /* attribute index */
    int32 attr_type, attr_size;     /* attribute type and size */
    char attr_name[40];  



    ret = SDfileinfo(in_sd_id, &nsds, &nattr);
    printf("nattr is %d\n", nattr);
    /* test to see if num_datasets and num_global_attr can be retrieved from in_sd_id */
    if (ret == -1)
        {
        fprintf(stdout, "cannot read information from input file \n");
        exit(EXIT_FAILURE);
        }
    else
        {
        /* loop through each global attributes */
        for (attr_index=0; attr_index<nattr; attr_index++)
        {
            printf("attr_index:nattr is %d:%d\n", attr_index, nattr);
            /* test to see if the file or dataset do indeed contain attributes */
            if (SDattrinfo(in_sd_id, attr_index, attr_name, &attr_type, &attr_cnt) == FAIL)
            fprintf(stdout, "Cannot read information for attribute %d\n", attr_index);
            else
            {
                DO SOMETHING 
            }
        }
    }
}

問題はnattr変数にあります。たとえば、ループ内での値を出力nattrすると、いつかはそれが得られますが、突然 のような巨大な数に爆発します。残りのコードでは、この変数を使用して他に何もしていません。私はそれをダブルとトリプルでチェックしました。ですから、なぜ突然爆発するのかわかりません。1 つのサンプル実行からのデバッグ ステートメントを以下に示します。11fornattr111869501279nattr

nattr is 11
attr_index:nattr is 0:11
attr_index:nattr is 1:11
attr_index:nattr is 2:11
attr_index:nattr is 3:11
attr_index:nattr is 4:11
attr_index:nattr is 5:11
attr_index:nattr is 6:11
attr_index:nattr is 7:11
attr_index:nattr is 8:1869501279
attr_index:nattr is 9:1850957672
attr_index:nattr is 10:1850957672
attr_index:nattr is 11:1850957672
Cannot read information for attribute 11
attr_index:nattr is 12:1850957672
Cannot read information for attribute 12
attr_index:nattr is 13:1850957672

ここで何が起こっているのかについての助け。ありがとう

4

1 に答える 1

5

あなたは(非常に)おそらくバッファオーバーフローを起こしています。attr_nameより大きいインデックスに書き込もうとしているに違いありません39

ただし、のサイズを大きくするだけではありませんattr_name。コードで何をしているのかを理解する必要があり// DO SOMETHINGます。

于 2014-08-27T14:36:22.897 に答える