Reputation: 13
I have a rather large c-code base, where every once in a while int is used instead of time_t. Any good ideas as to how to deal with this. Should I search the entire standard library for functions that either return time_t or take it as argument, or is there a smarter way?
As I understand it, time_t will be 64 bit on a 64-bit system, at least on my system, which is 64 bit. An int will only be 32 bit on a 64-bit system. Which means that such an int will run out in 2038 if used as time_t.
Upvotes: 1
Views: 122
Reputation: 225344
Assuming you're using gcc or clang, if you compile with the -Wconversion
flag, it will warn you about converting from a larger type to a smaller type.
#include <stdio.h>
#include <time.h>
int main()
{
time_t t = time(NULL);
int i = t;
printf("i=%d, t=%ld\n", i, t);
return 0;
}
[dbush@db-centos7 ~]$ gcc -g -Wall -Wextra -Wconversion -o x1 x1.c
x1.c: In function ‘main’:
x1.c:7:5: warning: conversion to ‘int’ from ‘time_t’ may alter its value [-Wconversion]
int i = t;
^
Upvotes: 2
Reputation: 2322
In the scenario you mention, (64-bit system, 32-bit integer) enabling compiler warnings, or use of a good static analysis program should highlight all the cases of implicit narrowing conversion of a 64-bit (time_t) integer to a 32-bit integer.
If you are using MISRA C:2012/2023, Rule 10.3 also applies...
So (for example):
time_t nowTime1 = clock(); /* OK */
int nowTime2 = clock(); /* Implicit narrowing to 32 bits */
unsigned int nowTime3 = clock(); /* Implicit narrowing to 32 bits */
uint32_t nowTime4 = clock(); /* Implicit narrowing to 32 bits */
However:
uint64_t nowTime5 = clock(); /* Probably OK */
unsigned long nowTime6 = clock(); /* Probably OK */
See also time()
and mktime()
, as well as clock()
.
Assuming all your sources are the correct size, then any sinks (ctime()
, difftime()
etc) should be OK...
Upvotes: 0