Thread: Odd Segmentation Fault

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Aug 2010
    Posts
    4

    Odd Segmentation Fault

    I wrote a program that includes the following code:

    Code:
    struct time     /* Structure for time variables */
    {
            int month;
            int day;
            int year;
    
            int hr;
            int min;
    };
    
    ...
    
            struct time time1,time2;
    
            printf("Start moment:  ");
            fgets(line,sizeof(line),stdin);
            sscanf
            (
                    line,
                    "%d/%d/%d %d:%d",
                    &time1.month, &time1.day, &time1.year, &time1.hr, &time1.min
            );
    The compiler (gcc) doesn't issue any warnings.

    As soon as I enter the start moment, the program terminates, like so:

    Code:
    greg@snapdragon:~/Programs/Oua/mindiff$ ./a.out
    Start moment:  8/12/1982 9:01
    Segmentation fault
    Interestingly, NO such segmentation fault occurs in the following cases:

    Code:
    struct date {
            int month;
            int day;
            int year;
    };
    
    ...
    
            printf("Date 1:  ");
            fgets(line,sizeof(line),stdin);
            sscanf(line,"%d/%d/%d",&date1.month,&date1.day,&date1.year);
    There is also no problem at all with this code:

    Code:
    struct time {
            int hr;
            int min;
    };
    
    ...
    
            printf("Time 1:  ");
            fgets(line,sizeof(line),stdin);
            sscanf(line,"%d:%d",&time1.hr,&time1.min);
    I thought the problem might be the space, and tried
    Code:
            printf("Start moment:  ");
            fgets(line,sizeof(line),stdin);
            sscanf
            (
                    line,
                    "%d/%d/%d,%d:%d",
                    &time1.month, &time1.day, &time1.year, &time1.hr, &time1.min
            );
    (with a comma instead of a space in the input), but that didn't help; still got a segmentation fault!

    I'm completely baffled. Does anybody know what is causing the problem?
    Last edited by JohnnyAppleseed; 08-24-2010 at 09:25 AM. Reason: Thought of something I should have mentioned.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault
    By bennyandthejets in forum C++ Programming
    Replies: 7
    Last Post: 09-07-2005, 05:04 PM
  2. Segmentation fault
    By NoUse in forum C Programming
    Replies: 4
    Last Post: 03-26-2005, 03:29 PM
  3. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 01:33 PM
  4. Segmentation fault...
    By alvifarooq in forum C++ Programming
    Replies: 14
    Last Post: 09-26-2004, 12:53 PM
  5. odd segmentation fault occurence
    By gazsux in forum C Programming
    Replies: 6
    Last Post: 12-13-2002, 09:02 AM

Tags for this Thread