C变量突然爆发

srs*_*sci 0 c variables int32

我在一段相当简单的代码上遇到了一个奇怪的问题.代码的相关部分如下:

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 
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题在于nattr变量.比如说nattr应该是11,在for我打印价值的循环中nattr,我得到它11的时间但是然后它突然爆炸到一个更大的数字1869501279.我nattr在其余的代码中没有对这个变量做任何其他事情.我有双重和牛肚检查.所以我不确定它为什么突然爆炸.下面给出了一个示例运行的调试语句:

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
Run Code Online (Sandbox Code Playgroud)

关于这里可能会发生什么的任何帮助.谢谢

pmg*_*pmg 5

你(非常)可能有缓冲区溢出.我敢打赌你要写的attr_name索引大于39.

但不要只是增加大小attr_name.您需要了解您在// DO SOMETHING代码中正在做什么.