我试图找出时间将溢出 time_t 值的日期
#include <stdio.h>
#include <time.h>
#include <limits.h>
main(){
time_t now,end;
now=time(NULL);
end=LONG_MAX;
printf("Current date : %s\n",ctime(&now));
printf("Date of death : %s\n",ctime(&end));
}
我发现在我的系统上 time_t 和 LONG_MAX 一样是 8 个字节。当我运行它时,我得到:
当前日期:2015 年 2 月 1 日星期日 17:29:09 和,死亡结束日期:(null)
但是当我设置 end=INT_MAX;
我得到 Date of Death : Tue Jan 05:14:07 2038 那么为什么我得到 (null) with LONG_MAX?而不是正常的约会
最佳答案
64 位长将在 292,277,026,596 年左右的某个地方进行环绕,这是从现在算起的宇宙当前年龄的 20 倍左右。由于地球自转不太可能一直持续到那个时候,人们也不会真正关心,所以那个时候很容易返回 (null)
。
开个玩笑,真正的原因很可能是 ctime
算法可能使用 localtime
将 time_t
转换为故障时间,而那使用 int
作为年份值。
以下 python 脚本可用于查找 time_t
的最大值,ctime
不会抛出异常(它是 libc ctime
,C 中的实现留给读者作为练习):
import time
t = 0
for i in range(56, -1, -1):
try:
newt = t + (2 << i)
time.ctime(newt)
t = newt
except ValueError:
pass
print("Maximum value", bin(t))
print("Date at maximum", time.ctime(t))
我电脑上的代码输出,glibc 2.19:
Maximum value 0b11110000110000101001110110000110100010111110000101011010
Date at maximum Tue Dec 31 23:59:52 2147483647
2147483647 是 2 ^ 31 - 1。
关于c - time_t 环绕日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28264458/