我在一段相当简单的代码上遇到了一个奇怪的问题。代码的相关部分如下:
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
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
变量执行任何其他操作。我有双重和牛肚检查。所以我不确定它为什么突然爆炸。下面给出了一个样本运行的调试语句:
{{1}}
有关此处可能发生的事情的任何帮助。 感谢
答案 0 :(得分:5)
你(非常)可能有缓冲区溢出。我敢打赌,您正试图向attr_name
写入大于39
的索引。
但不要只增加attr_name
的大小。您需要了解// DO SOMETHING
代码中的内容。