我在一段相当简单的代码上遇到了一个奇怪的问题。准则的相关部分如下:
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
有什么可以帮忙的吗。
谢谢
最佳答案
你可能有一个缓冲区溢出。我敢打赌,你是在试图将attr_name
写入大于39
的索引。
但不要只增加attr_name
的大小。您需要了解您在// DO SOMETHING
代码中所做的工作。