Thread: Where's my seg fault?

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    55

    Where's my seg fault?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    
    {
    
     
    FILE *ofp;
    
    FILE *ifp;
    
    
    int input;
    int sum = 0;
    int output[60];
    char filename[50];
    
    
    //Opens the file being printed to
     
    ofp = fopen("output.dat", "w");
    
    if(ofp == NULL)
       {
    
        printf("Unable to open output.dat for writing\n");
        exit(1);
    
       }
    
    
    //Opens up the file with numbers in it
    
    ifp = fopen("pix.dat", "r");
    
    
    if(ifp == NULL)
       {
    
        printf("Unable to open pix.dat\n");
        exit(1);
    
       }
    
    int i = 0;
    
    fscanf(ifp, "%d", &input);
    
    while ( !feof(ifp) )
    {
      
      printf("test");
      output[i] = input;
      
      i++;
      sum++;
      fscanf(ifp, "%d", &input);
    }

  2. #2
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Likely "i" is greater than 59
    Code:
    output[i] = input;
    Tim S.

  4. #4
    Registered User
    Join Date
    Jan 2011
    Posts
    55
    I know that's bad. That's not where the seg fault is happening though. I'm not focused on proper practice of feof(). Thank you for the useful info though!

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Look up fscanf() in your C library documentation (What's that? Don't have it? Get it!) and pay special attention to the value it returns.
    Code:
    int i, sum;
    
    i = 0;
    sum = 0;
    while ( fscanf(ifp, "%d", &input) > 0 )
    {
      output[i] = input;
      i++;
      sum += input;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with seg fault
    By homer_3 in forum C Programming
    Replies: 3
    Last Post: 02-05-2010, 01:33 PM
  2. Seg Fault :(
    By kentadams in forum C Programming
    Replies: 6
    Last Post: 09-07-2007, 04:18 PM
  3. Seg fault
    By Tommo in forum C Programming
    Replies: 40
    Last Post: 08-28-2007, 07:12 AM
  4. SP2 fault
    By caroundw5h in forum Windows Programming
    Replies: 1
    Last Post: 11-06-2004, 07:45 PM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 11:09 PM