搜索 int 使用而不是 time_t 的用途

问题描述 投票:0回答:2

我有一个相当大的c代码库,其中每隔一段时间就会使用int而不是time_t。关于如何处理这个问题的任何好主意。我应该在整个标准库中搜索返回 time_t 或将其作为参数的函数,还是有更聪明的方法?

据我了解,time_t在64位系统上将是64位,至少在我的64位系统上是这样。 int 在 64 位系统上只能是 32 位。这意味着这样一个 int 如果用作 time_t 将会在 2038 年用完。

c std time-t
2个回答
0
投票

在您提到的场景中,(64位系统,32位整数)一个好的静态分析程序应该突出显示64位(time_t)整数到32位整数的隐式收缩转换的所有情况。

如果您使用 MISRA C:2012/2023,规则 10.3 也适用...

所以(例如):

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

但是:

uint64_t      nowTime5 = clock(); /* Probably OK */
unsigned long nowTime6 = clock(); /* Probably OK */

另请参阅

time()
mktime()
,以及
clock()

假设所有源的尺寸都正确,那么任何水槽(

ctime()
difftime()
等)都应该没问题...


0
投票

假设您使用的是 gcc 或 clang,如果您使用

-Wconversion
标志进行编译,它会警告您从较大类型转换为较小类型。

#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;
     ^
© www.soinside.com 2019 - 2024. All rights reserved.