# scanf and time_t segmentation fault



## dead_rabbit (Jul 17, 2011)

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 

```
#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 
	
	



```
Segmentation fault: 11 (core dumped)
```
 any insight?


----------



## fonz (Jul 17, 2011)

Works just fine on my system. Can you provide a stack trace or something?

Fonz


----------



## xibo (Jul 17, 2011)

_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?


----------



## fonz (Jul 17, 2011)

*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:
	
	



```
#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:
	
	



```
#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


----------



## dead_rabbit (Jul 17, 2011)

Thanks a bunch Fonz! I tried explicitly casting _time_t_ to _long int_ as you suggested above and every thing is well now


----------

