简体   繁体   中英

End Of Array Segmentation Fault

I have a strange-looking problem that I've encountered while trying to draw a few circles digitally, using C.

What seems to be happening is that the printing-out part of the code works as intended. It prints out every single item in the array. The error comes right at the end - immediately after the last item is printed out, the terminal throws out a segmentation fault.

After a bit of testing, I concluded that this happens every time I try to print out an element in the array, whether I'm printing out the full thing or just a part of it. I even tried just printing out the first "line" of the array - it returned the line just fine, but threw that same fault afterwards.

I'm a complete beginner in C, but suspect that the problem lies in having overwrote the null terminator in my array. Whether this is nor is not the case, I'm not sure how to fix this problem. Any suggestions?

#include <stdio.h>
#define EW 707
#define EH 600

int ec[EH][EW][3] ;
int main(void)
{
   int y , x , blah ;
   char arr[80] ;
   FILE* fin ;
   fin = fopen( "input.ppm" , "r" ) ;
   fscanf( fin , "%s" , arr   ) ;
   fscanf( fin , "%d" , &blah ) ; 
   fscanf( fin , "%d" , &blah ) ; 
   fscanf( fin , "%d" , &blah ) ; 

   for( y = 0 ; y < EH ; y++ )
   {
   for( x = 0 ; x < EW ; x++)
      {
         fscanf( fin , "%d" , ec[y][x] + 0 ) ;
         fscanf( fin , "%d" , ec[y][x] + 1 ) ;
         fscanf( fin , "%d" , ec[y][x] + 2 ) ;
      }
   }
   close( fin ) ;
   for(y = 0; y < EH; y++)
   {
       for(x = 0; x < EW; x++)
       {
           for(blah = 0; blah < 3; blah++)
           {
               printf("%d %d %d \n", y, x, blah);
               printf("%d \n", ec[y][x][blah]);
           }
       }
  }

}

Your code appears to be working.

The only "strangeness" I see is that you use close on fin instead of fclose , which might cause problems. Also, it shows you're not running the compiler with all warnings enabled.

If you cannot better pinpoint the source of trouble, try running the executable under valgrind . I did, but not having a PPM handy, I replaced all reads with assignments of a fixed value; try doing the same (assign all pixels to 0, for example), and if this "cures" the problem, then it is something in your file format that's causing troubles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM