ctime 返回 null
如果用户类型 time_t
定义为 __darwin_time_t
,它本身在 MacOS X 中定义为 long
,为什么下面的代码会输出 8 时间是(空)
?也许这很愚蠢,但我真的无法理解。
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t time = 0x7FFFFFFFFFFFFFFF;
printf("%lu\n"
"Time is %s\n", sizeof(time_t), ctime(&time));
return 0;
}
If the user type time_t
is defined as __darwin_time_t
, which itself is defined as long
in MacOS X, why does the following code outputs 8 Time is (null)
? Maybe it's something silly, but I can't really understand it.
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t time = 0x7FFFFFFFFFFFFFFF;
printf("%lu\n"
"Time is %s\n", sizeof(time_t), ctime(&time));
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
时间 0x7FFFFFFFFFFFFFFFF 似乎是公元 292,471,210,647 年左右,这无疑会导致 ctime 超过 C99 保证的 26 个字符,因此它返回 NULL 而不是溢出其缓冲区。一般来说,尽量避免发生在莫洛克人与埃洛伊人交战之后的任何日期。
Time 0x7FFFFFFFFFFFFFFF appears to be around the year 292,471,210,647 AD, which undoubtedly causes
ctime
to exceed the 26 characters it is guaranteed by C99, so it returns NULL rather than overflowing its buffer. In general, try to avoid any dates that occur after the Morlocks go to war with the Eloi.在阅读《专家 C 编程》一书时,我在 Lion 10.7.3 中遇到了同样的问题——
t=0xf0c00000000000
,ctime(&t)
产量Wed Mar 1 21:07:12 214739252
并使用t=0xf0d00000000000,ctime(&t)
返回空指针 (0x0)。因此,它似乎不是 t 的环绕,而是
ctime(&t)
内部的一些测试,如果 t 太大,则返回空指针。While working through the book "Expert C Programming", I ran across the same problem in Lion 10.7.3 -- with
t=0xf0c00000000000
,ctime(&t)
yieldsWed Mar 1 21:07:12 214739252
and witht=0xf0d00000000000, ctime(&t)
returns the null pointer (0x0).So it doesn't appear to be a wrap around for t, but some test inside
ctime(&t)
that returns the null pointer if t is too large.来自 glibc 的实现我们读到:
运行下面的程序来查找您计算机上的确切限制。
对我来说,结果是
Tue Dec 31 23:59:59 2147483647
,这恰好是该年溢出四个有符号字节之前的第二个。From glibc's implementation we read:
Run the program below to find the exact limit on your machine.
For me that comes out to
Tue Dec 31 23:59:59 2147483647
which happens to be the second before the year overflows four signed bytes.