scanf and time_t segmentation fault

I was working on a program which reads a input in seconds from the user. This program compiles fine but when I enter a value for the seconds it crashes. I used this program to test the assignment of a value to a time_t variable
Code:
#include<stdio.h>
#include<time.h>

int main() {

    time_t t;
    scanf("%lld", &t);
    printf("%lld\n", t);
    return 0;
}
But when I execute this code, after entering a number, I get
Code:
Segmentation fault: 11 (core dumped)
any insight?
 
lld expects long long decimal, which is usually a 64 bit integer. What's the length of a time_t on your machine, and especially, is sizeof(time_t) == sizeof(long long int) true?
 
Maybe this will solve your problem?

A couple of remarks:
  • For starters, I try to avoid long long int because C90 doesn't allow it.
  • time_t is usually a long int, not a long long int.
  • Try the following on your machine:
    Code:
    #include <stdio.h>
    #include <time.h>
    
    int
    main()
    {
      printf("%d %d %d\n",sizeof(long int),sizeof(long long int),sizeof(time_t));
      return 0;
    }
    On an i386 I get the output 4 8 4 (in other words: time_t is a long int). On an amd64 I get the output 8 8 8 (in other words: there's no difference between long int and long long int). This explains why your code segfaults on an i386 but works just fine on an amd64.
  • Did you use any warning flags at all? If I compile your code with -Wall I get warnings about type differences.
  • The most likely solution is to use ld instead of lld. When I try that your code works fine even on the i386.
  • To get rid of any warnings, explicitly cast the time_t to long int as follows:
    Code:
    #include <stdio.h>
    #include <time.h>
    
    int
    main()
    {
      time_t t;
      scanf("%ld",(long int*)&t);
      printf("%ld\n",(long int)t);
      return 0;
    }
Hope this helps,

Fonz
 
Thanks a bunch Fonz! I tried explicitly casting time_t to long int as you suggested above and every thing is well now :)
 
Back
Top