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?