2014-08-27 3 views
0

상당히 단순한 코드에 이상한 문제가있다. nattr 변수로하는 문제C 변수가 갑자기 날아 오른다.

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 
      } 
     } 
    } 
} 

: 코드의 관련 부분에 대해서 설명한다. 예를 들어 nattr11이어야하며, nattr의 값을 인쇄 할 때 루프 내에서 나는 11으로 표시되지만 언젠가는 1869501279과 같은 huger 번호로 불어납니다. 나머지 코드에서이 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

스택 손상? –

+11

아마도 버퍼 오버플로가있을 것입니다. 나는 당신이 39보다 큰 인덱스를 만들기 위해'attr_name'에 쓰려고 노력할 것이라고 확신합니다. – pmg

+0

대단한 !! 최고 ** Piotr S ** 및 ** pmg **. 'attr_name' 배열을 더 높은 크기로 설정하면 그것을 고정시킵니다. 감사는 새로운 것을 배웠습니다. – srsci

답변

5

아마도 버퍼 오버플로가있을 수 있습니다. 39보다 큰 인덱스에 attr_name에 글을 쓰려고합니다.

그러나 단지 크기를 늘리지 마십시오. attr_name. // DO SOMETHING 코드에서 수행중인 작업을 이해해야합니다.

+0

나는 어쨌든 그것의 한계를 넘어서서 쓸 수있는 나머지 코드에서'attr_name'을 사용하여 다른 것을하지 않을 것입니다. 'SDattrinfo '에 대한 그 호출은 그것이 설정되는 유일한 장소입니다. 또한 크기를 알 수있는 다른 방법이 없기 때문에 미리 정해진 크기로가 아닌'attr_name'을 동적으로 설정할 수 있습니다. – srsci

+0

어레이 크기를 늘리는 것이 유용한 해결책입니다. @WhozCraig가 연결된 페이지에는 "Wednesday, July 29, 1998 20:31:40 Wednesday"의 타임 스탬프가 있습니다. 어쩌면 당신은 더 최근의 라이브러리를 찾을 수 있습니다 :) – pmg

+0

'attr_name'의 크기에 대한 아이디어를 얻기 위해 사용할 수있는 다른 함수 API가 없기 때문에 고정 버퍼 이외에 무엇을 해야할지 모른다 !! – srsci

관련 문제