Thread: Getting a segmentation fault.

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    117

    Getting a segmentation fault.

    Hello,

    Still working on the same project if you have seen me post before.
    Almost finished though. I'm working on the project where I have to take files that have multiple lines that look like this....

    Tuesday,17
    Wednesday,57
    Friday,27
    Tuesday,17

    Anyways I have to see how many times each day is in each file. And I have to add up the number by that particular day.

    Tested code and it ran smoothly the first file, but then gives me a segmentation fault the next time it tries to run one. I'm assuming that's me messing up on the pointers or something of the sort.
    Any help would be great.
    Thanks

    Here's my code...

    Btw it's the same loop twice. One is for the first 9 files, then the other one is for all of the double digit files.
    Also I'm working on changing the counters to array's as we speak.

    Code:
    #include <stdio.h>#include <stdlib.h>
    
    
     
    int main(void)
     {
         int day1total = 0;
         int day2total = 0;
         int day3total = 0;
         int day4total = 0;
         int day5total = 0;
         int day6total = 0;
         int day7total = 0;
         int day1number = 0;
         int day2number = 0;
         int day3number = 0;
         int day4number = 0;
         int day5number = 0;
         int day6number = 0;
         int day7number = 0;
         int i = 1;
         int n;
         int file_count = 1;
         char buffer[50];
         char day[50];
         FILE *fp;
         char filename[50];
    
    
    while ( i < 10 ) 
    {
         
       sprintf(filename,"hw04-data-0%d.csv", i);
       fp=fopen(filename, "r");
    
    
       
    
    
       while(fgets(buffer, sizeof(buffer), fp))
        {
          sscanf(buffer,"%[^,] ,%d", day, &n);
          /*printf("day is %s, amt is %d\n", day, n);*/
    
    
                 if(strcmp(day, "Sunday")==0) 
                       {
                        day1total++;
                        day1number+=n;
                        }
     
                 if(strcmp(day, "Monday")==0) 
                       {
                        day2total++;
                        day2number+=n;
                       }
                 
                 if(strcmp(day, "Tuesday")==0) 
                       {
                        day3total++;
                        day3number+=n;
                       } 
    
    
                 if(strcmp(day, "Wednesday")==0) 
                       {
                        day4total++;   
                        day4number+=n;
                       } 
                 if(strcmp(day, "Thursday")==0) 
                       {
                        day5total++;
                        day5number+=n;
                       }
    
    
    
    
                 if(strcmp(day, "Friday")==0) 
                       {
                        day6total++;
                        day6number+=n;
                       }             
                       
                 if(strcmp(day, "Saturday")==0) 
                       {
                        day7total++;
                        day7number+=n;
                       } 
    
    
    
    
    }
    printf("File %2d:  Sun, %d, %d; Mon, %d, %d; Tue, %d, %d; Wed,"
           "%d, %d; Thu, %d, %d; Fri, %d, %d; Sat, %d, %d\n",     file_count, day1total, day1number, day2total, day2number, day3total, day3number, day4total, 
                                                                   day4number, day5total, day5number, day6total, day6number, day7total, day7number);
    file_count++;             
    
    
          day1total = 0;
          day2total = 0;
          day3total = 0;
          day4total = 0;
          day5total = 0;
          day6total = 0;
          day7total = 0;
          day1number = 0;
          day2number = 0;
          day3number = 0;
          day4number = 0;
          day5number = 0;
          day6number = 0;
          day7number = 0;
    i++;
    
    
    }
    
    
    
    
    
    
    i=10;
    
    
    while ( i < 100 ) 
    {
         
       sprintf(filename,"hw04-data-%d.csv", i);
       if((fp=fopen(filename, "r")) == NULL) 
       {
          printf("Error: file failed to open!\n");
          getchar();
          return 1;
       }
    
    
       
    
    
       while(fgets(buffer, sizeof(buffer), fp))
        {
          sscanf(buffer,"%[^,], %d",day, &n);
        
    
    
                 if(strcmp(day, "Sunday")==0) 
                       {
                        day1total++;
                        day1number+=n;
                        }
     
                 if(strcmp(day, "Monday")==0) 
                       {
                        day2total++;
                        day2number+=n;
                       }
                 
                 if(strcmp(day, "Tuesday")==0) 
                       {
                        day3total++;
                        day3number+=n;
                       } 
    
    
                 if(strcmp(day, "Wednesday")==0) 
                       {
                        day4total++;   
                        day4number+=n;
                       } 
                 if(strcmp(day, "Thursday")==0) 
                       {
                        day5total++;
                        day5number+=n;
                       }
    
    
    
    
                 if(strcmp(day, "Friday")==0) 
                       {
                        day6total++;
                        day6number+=n;
                       }             
                       
                 if(strcmp(day, "Saturday")==0) 
                       {
                        day7total++;
                        day7number+=n;
                       }              
    
    
    }
    
    
    printf("File %2d:  Sun, %d, %d; Mon, %d, %d; Tue, %d, %d; Wed,"
           "%d, %d; Thu, %d, %d; Fri, %d, %d; Sat, %d, %d\n",     file_count, day1total, day1number, day2total, day2number, day3total, day3number, day4total, 
                                                                   day4number, day5total, day5number, day6total, day6number, day7total, day7number);
    file_count++;             
    
    
          day1total = 0;
          day2total = 0;
          day3total = 0;
          day4total = 0;
          day5total = 0;
          day6total = 0;
          day7total = 0;
          day1number = 0;
          day2number = 0;
          day3number = 0;
          day4number = 0;
          day5number = 0;
          day6number = 0;
          day7number = 0;
    i++;
    }
    
    
    getchar();
    return 0;
    }

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    1. You need to check for fopen failure on line 34.
    2. You need to close your file when you're done with it (after your while (fgets...) loop).
    3. You can combine the loops. To get the right file name, use d in your sprintf(filename, ...), which will make sure the number is two digits and zero-padded.

  3. #3
    Registered User
    Join Date
    Feb 2012
    Posts
    117
    Sorry if this is a stupid question but what do you mean on number 3 add a d to make sure it's double padded?

    And also how do I check the file opening failure?

    I put fclose(fp); in there.
    Glad you noticed that, I need to make a habit of putting it in before I even start to write the code.

  4. #4
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    anduril meant to say %02d (that's a zero before the two). So like this:
    Code:
    sprintf(filename,"hw04-data-%02d.csv", i);
    Just remember that whenever you find yourself copying/pasting big sections of code, there's probably a better way to do it.

    Also, whenever you find yourself using a bunch of variables that only differ by a number, you probably should be using arrays.
    Code:
    int total[7];
    int number[7];
    
    // Access them with indices 0 to 6. So, for Sunday:
    total[0]++;
    number[0] += n;
    
    // Zero them in a loop:
    for (j = 0; j < 7; j++)
        total[j] = number[j] = 0;

  5. #5
    Registered User
    Join Date
    Feb 2012
    Posts
    117
    Ok that makes sense to me on the number thing for the file. Except that I'm going to have files that are for example 59, 83, 99. So there will be no 0 in those. So I'll show you the code I came up with....

    1.) I put fclose in there so that part should be fixed.
    3.) The whole program runs on one loop now.
    But 2.) How do I check if fopen is working correctly? See I'm using Dev-C and it's running fine. But when I do this in gcc/ssh it doesn't work fine. After the first file is printed it says segmentation fault.


    edit...hold on I think I made a mistake...I think i misread what you meant by %0d. I don't even need that loop with j.
    p.s. thanks for the advice on remembering if I have to copy and paste a lot there's an easier way to do it.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    int main(void)
     {
         int count[100]= {0};
         int total[8]={0};
         int i = 1;
         int j = 0;
         int k = 0;
         int n;
         int file_count = 1;
         char buffer[50];
         char day[50];
         FILE *fp;
         char filename[50];
    
    while ( file_count < 100 ) 
    {
         
       sprintf(filename,"hw04-data-%d%d.csv", j, i);
       fp=fopen(filename, "r");
    
       while(fgets(buffer, sizeof(buffer), fp))
        {
          sscanf(buffer,"%[^,] ,%d", day, &n);
    
    
                 if(strcmp(day, "Sunday")==0) 
                       {
        count[0]++;
        total[0] += n;
                        }
     
                 if(strcmp(day, "Monday")==0) 
                       {
        count[1]++;
        total[1] += n;
                       }
                 
                 if(strcmp(day, "Tuesday")==0) 
                       {
        count[2]++;
        total[2] += n;
                       } 
    
                 if(strcmp(day, "Wednesday")==0) 
                       {
        count[3]++;
        total[3] += n;
                       } 
                 if(strcmp(day, "Thursday")==0) 
                       {
        count[4]++;
        total[4] += n;
                       }
    
    
                 if(strcmp(day, "Friday")==0) 
                       {
        count[5]++;
        total[5] += n;
                       }             
                       
                 if(strcmp(day, "Saturday")==0) 
                       {
        count[6]++;
        total[6] += n;
                       } 
        }
    
    printf("File %2d:  Sun, %d, %d; Mon, %d, %d; Tue, %d, %d; Wed,"
           "%d, %d; Thu, %d, %d; Fri, %d, %d; Sat, %d, %d\n",     file_count,  count[0], total[0], count[1], total[1], count[2], total[2], 
                                                                               count[3], total[3], count[4], total[4], count[5], total[5], count[6], total[6]);
    // Close the open file                                                                           
    fclose(fp);                                                                           
    file_count++;             
    
    // Zero them in a loop
    for (k = 0; k < 7; k++)
        total[k] = count[k] = 0;
    
    // Increase j every 10 files.
    i++;
    if(i == 10 || i == 20 || i == 30 || i == 40 || i == 50 || i == 60 || i == 70 || i == 80 || i==90 )
         {
             j++;
             i=0;
         }
    }
    
    getchar();
    return 0;
    }
    Last edited by mgracecar; 02-22-2012 at 08:19 PM.

  6. #6
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    That's more complicated than it needs to be. This
    Code:
    sprintf(filename,"hw04-data-%02d.csv", i);
    will produce:
    hw04-data-01.csv
    hw04-data-02.csv
    hw04-data-03.csv
    ...
    hw04-data-10.csv
    hw04-data-11.csv
    ...
    hw04-data-99.csv

    for i from 1 to 99.

    The 2 in %02d means to write the number in a field of length 2. The 0 before the 2 means to "pad" the field with zeros instead of spaces.
    Last edited by oogabooga; 02-22-2012 at 08:24 PM.

  7. #7
    Registered User
    Join Date
    Feb 2012
    Posts
    117
    Yea, that's my bad lol. I saw that right after I posted this and felt really foolish

    But I changed it to where it just uses

    Code:
       sprintf(filename,"hw04-data-%02d.csv", i);
    as you said. and increment i every file.

    Could you please advise me in how to check that they are opening correctly? Or would that even be the problem? First file prints everything perfectly then goes to a new line and prints segmentation fault.

  8. #8
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    You're supposed to check that fp is non-null after fopen. Something like this:
    Code:
    fp=fopen(filename, "r");
    if (!fp) {
        fprintf(stderr, "Couldn't open file: %s\n", filename);
        continue;  // go to top of outer loop
    }
    BTW, count and total only have to be size 7. And file_count is really the same thing as i.

  9. #9
    Registered User
    Join Date
    Feb 2012
    Posts
    117
    Yea I changed the i out for file_count because I noticed that too.

    I tried your


    Code:
    fp=fopen(filename, "r");
    if (!fp) {
        fprintf(stderr, "Couldn't open file: %s\n", filename);    continue;  // go to top of outer loop
    }

    But continue seemed to create an infinite loop. It just kept printing the Couldn't open file over and over.

    So I changed continue with exit(1)
    and it printed the Couldn't open file once.

    But either way that means it's still not opening the 2nd file I believe. Or something along those lines?


    I also tried this because it's the way our teacher taught us how to check for NULL and it's printing the same thing...

    Code:
    if ( (fp = fopen(filename, "r" )) == NULL )
        {
        printf("Couldn't open file\n");
        exit(1); 
        }
    Here is my revised code as of now. So the only problem should be opening the next file, or maybe I'm closing the first file incorrectly.

    Code:
    int main(void)
     {
         /* Declares all variables needed */         
         int count[7]= {0}; 
         int total[7]={0};
         int j = 0;
         int n;
         int file_count = 1;
         char buffer[50];
         char day[50];
         FILE *fp;
         char filename[50];
    
    
         /* While loop that goes through each file */
    while ( file_count < 100 ) 
    {
         /* Takes each filename and stores in array "filename" */  
       sprintf(filename,"hw04-data-%02d.csv", file_count);
    
    
         /* Opens the file */
       if ( (fp = fopen(filename, "r" )) == NULL )
        {
        printf("Couldn't open file\n");
        exit(1); 
        }
    
    
         /* While loop that gets the file and stores the string in "day" and the number in "n" */
       while(fgets(buffer, sizeof(buffer), fp))
        {
          sscanf(buffer,"%[^,] ,%d", day, &n);
    
    
         /* Seven if loops adding the number of times a day was seen, storing it in the count spot for that day */
         /* and getting the number after the week and adding it to the total spot for that day */ 
                 if(strcmp(day, "Sunday")==0) 
                       {
        count[0]++;
        total[0] += n;
                        }
     
                 if(strcmp(day, "Monday")==0) 
                       {
        count[1]++;
        total[1] += n;
                       }
                 
                 if(strcmp(day, "Tuesday")==0) 
                       {
        count[2]++;
        total[2] += n;
                       } 
    
                 if(strcmp(day, "Wednesday")==0) 
                       {
        count[3]++;
        total[3] += n;
                       } 
                 if(strcmp(day, "Thursday")==0) 
                       {
        count[4]++;
        total[4] += n;
                       }
    
                 if(strcmp(day, "Friday")==0) 
                       {
        count[5]++;
        total[5] += n;
                       }             
                       
                 if(strcmp(day, "Saturday")==0) 
                       {
        count[6]++;
        total[6] += n;
                       } 
        }
    
    
    printf("File %2d:  Sun, %d, %d; Mon, %d, %d; Tue, %d, %d; Wed,"
           "%d, %d; Thu, %d, %d; Fri, %d, %d; Sat, %d, %d\n",     file_count,  count[0], total[0], count[1], total[1], count[2], total[2], 
                                                                               count[3], total[3], count[4], total[4], count[5], total[5], count[6], total[6]);
    /* Close the open file */                                                                          
    fclose(fp);                                                                           
      
    /* Adds 1 to the loop and shows which file we are on */             
    file_count++;
    
    
    /* Zero them in a loop */
    for (j = 0; j < 7; j++)
        total[j] = count[j] = 0;
    }
    getchar();
    return 0;
    }

  10. #10
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    You're right about the infinite loop. I should've incremented file_count before the continue to go on and try the next file. But exit is good too.

    You need to check the actual filenames to see if your generated names match. Do a dir (or ls) of the directory and see what the names look like and that all the files are actually there.

    BTW, your indentation is getting a little sketchy.

  11. #11
    Registered User
    Join Date
    Feb 2012
    Posts
    117
    haha ok I'll fix the indentation. Sorry about that.
    It seems all the file names are hw-04-data-01.csv
    hw-04-data-01.csv
    etc.

    Weird, I guess I'll just have to mess around with it a little more and do a little more research. Thanks for all the help so far!

  12. #12
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    The two filenames you gave are identical. That can't be right, unless they're in different directories.

  13. #13
    Registered User
    Join Date
    Feb 2012
    Posts
    117
    Sorry I meant to write hw-04-data-02.csv
    Typo on my part.

    Anyways I found the problem.
    For some reason I didn't have

    hw-04-data-02.csv in my folder. I probably messed with it when I was moving folders or something. Anyways I moved that one back and the program works perfect.

    easy fix. But I guess it's better to have these stupid problems then really difficult ones =P

    Thanks for all your help oogabooga.

  14. #14
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    No problem. Remember that idea from the other thread about an array of the day names. It would allow you to compress the middle (repetitive) section of your code into a loop. If you're into it, that is.

    Also, I should mention that you should replace this
    Code:
    while ( file_count < 100 )
    with this
    Code:
    for ( file_count = 1; file_count < 100; file_count++ )
    A for loop collects all the relevant control info in one place.
    Last edited by oogabooga; 02-22-2012 at 09:25 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with segmentation fault!!!
    By Tiago Ferreira in forum C Programming
    Replies: 3
    Last Post: 05-31-2011, 07:34 AM
  2. segmentation fault
    By pshirishreddy in forum C Programming
    Replies: 3
    Last Post: 11-08-2008, 02:46 AM
  3. Segmentation fault
    By Ron in forum C Programming
    Replies: 14
    Last Post: 06-08-2006, 01:06 AM
  4. Segmentation fault
    By Calavera in forum C Programming
    Replies: 4
    Last Post: 11-18-2005, 08:19 AM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 11:09 PM