Search code examples
csegmentation-faultreadfile

Segmentation Fault in C when reading a file full of ints


I am simply trying to open a file and read the ints and print the array. However, a segmentation fault shows up. I am not sure what I am doing wrong.

int main (int argc, char *argv[])
{
   int size;
   int i;
   FILE* p = fopen(argv[1], "r");
   fscanf(p, "%d", &size);
   int a[size];

   for(i=0; i<size; i++)
   {
      a[i] = fscanf(p,"%d",&a[i]);

   }

   for(i=0;i<size;i++)
  {
      printf("%d", a[i]);
  }

}

Any help will be appreciated. Thanks.


Solution

  • The code looks fine, however you can add some validation to it to make sure your input is correct.

    int main (int argc, char *argv[])
    {
       int size=0;
       int i=0;
       int ret=0;
    
       // make sure arcv[1] exists:
       if (argc < 2)
       {
           printf("not enough arguments provided");
           return -1;
       }
    
       FILE* p = fopen(argv[1], "r");
    
       // make sure file exists
       if (p == 0) // or p == NULL
       {
           printf("file does not exists");
           return -1;
       }
    
       ret = fscanf(p, "%d", &size);
       // make sure the size is a valid number
       if (ret == EOF || ret <= 0 || size <= 0)
       {
           printf("invalid file");
           return -1;
       }
       int a[size];
    
       for(i=0; i<size; i++)
       {
          fscanf(p,"%d",a+i);
       }
    
       for(i=0;i<size;i++)
       {
          printf("%d", a[i]);
       }
    
    }