2014-05-02 44 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从不设置。