2014-05-02 40 views
2

當我繼續嘗試調試時,Int值'j'越來越奇怪。我不確定這是我的學校的編譯器的問題,還是我的代碼。謝謝您的幫助。int var越來越奇怪的值

GCC版本:/usr/local/lib/gcc-lib/sparc-sun-solaris2.7/2.95.2/specs gcc版本2.95.2 19991024(釋放)

閱讀規格

我的代碼段,其真實搞亂:

void sFlag(DIR * dirp, int c, char *dirname) 
    { 
     struct dirent *dp; 
     struct stat statbuf; 
     struct stat statarray[c]; 
     struct stat tempstat; 
     char fullfilename[MAXSZ]; 
     int i; 
     int boo; 
     int j; /*<--------- variable that's messing up*/ 

     while((dp = readdir(dirp)) != NULL) 
     { 
      snprintf(fullfilename, MAXSZ, "%s/%s", dirname, dp->d_name); 
      if(stat(fullfilename, &statbuf) == -1) 
       printf("Could not read file %s\n", dp->d_name); 
      else if(isHiddenFile(dp->d_name)) 
      { 
       statarray[i] = statbuf; 
       i++; 
      } 
     } 
/*As far as i know all the code above works fine*/ 

/*bubble sort that will sort array by logical file size*/ 
     while(boo) 
     { 
      j = 0; 
      boo = 0; 
      while(j < c) 
      { 
       fprintf(stderr, "%d\n", j); /*print debug info*/ 
       if(statarray[j].st_size < statarray[j+1].st_size) 
       { 
        tempstat = statarray[j]; 
        statarray[j] = statarray[j+1]; 
        statarray[j+1] = tempstat; 
        boo = 1; 
       } 
       j++; 
      } 
     } 
     for(j = 0; j < c; j++) 
     { 
      printf("%s\t%ld\t%s\n", dp->d_name, statarray[j].st_size, ctime(&statarray[j].st_mtime)); 
     } 
    } 

所以每次我運行此的fprintf中打印出的值對於j爲: -12975991 ???????它從哪裏得到這個數字? 顯然我得到一個數組索引越界的分段錯誤

有什麼想法?

+4

'while(j

+1

當你在調試器下運行你的代碼並且通過時,你並沒有注意到越界索引,我很驚訝。 –

+0

好的,謝謝你們,是的,當我有j的最後一個值時,它正在嘗試訪問statarray [5],這是超出界限,並搞砸了值。將它改爲j Ant

回答

1

你很可能會踐踏記憶並覆蓋j的內容。這個循環:

 while(j < c) 
     { 
      fprintf(stderr, "%d\n", j); /*print debug info*/ 
      if(statarray[j].st_size < statarray[j+1].st_size) 
      { 
       tempstat = statarray[j]; 
       statarray[j] = statarray[j+1]; 
       statarray[j+1] = tempstat; 
       boo = 1; 
      } 
      j++; 
     } 

注意,它訪問statarray[j+1],但statarray被定義爲

struct stat statarray[c]; 

這意味着在最後一次迭代,j+1 == c,這是出界。寫入數組中的該索引將踐踏堆棧中的其他內容,其中可能包括j,並解釋爲什麼會得到一個聽起來很古怪的值。

有一些漂亮的工具可以讓你更容易找到你可能會考慮的工具,如valgrind

1

在此塊中,

 while(j < c) 
     { 
      fprintf(stderr, "%d\n", j); /*print debug info*/ 
      if(statarray[j].st_size < statarray[j+1].st_size) 
      { 
       tempstat = statarray[j]; 
       statarray[j] = statarray[j+1]; 
       statarray[j+1] = tempstat; 
       boo = 1; 
      } 
      j++; 
     } 

您正在訪問未授權的存儲器時j等於c-1。這會搞砸了。在此之後,你無法期待可預測的行爲。

0

您在while循環中有一個新變量j,外部j從不設置。