【发布时间】:2013-10-12 00:50:51
【问题描述】:
仔细查看time.h几次后,我写了以下func:
void output_date ( int day, int month, int year ) {
char buffer[64] = "";
struct tm *e_time = calloc( (size_t) 1, sizeof(struct tm) );
e_time->tm_year = year - 1900;
e_time->tm_mon = month - 1;
e_time->tm_mday = day;
e_time->tm_hour = 0;
e_time->tm_min = 0;
e_time->tm_sec = 0;
e_time->tm_isdst = -1;
/* strftime ( buffer, 64, (char *)0, e_time ); */
strftime ( buffer, 64, "%a %b %e %H:%M:%S %Z (%z) %Y", e_time );
printf ( "%s\n", buffer );
free(e_time);
e_time = NULL;
}
然后我用一系列可能的输入调用了这个函数,但什么也没看到 像这样的奇怪输出:
Sun Jul 8 00:00:00 () 2013
Sun Jul 9 00:00:00 () 2013
Sun Jul 10 00:00:00 () 2013
Sun Jul 11 00:00:00 () 2013
Sun Jul 12 00:00:00 () 2013
当我将格式字符串测试为 strftime 时,我看到了很好的结果:
$ date -u "+%a %b %e %H:%M:%S %Z (%z) %Y"
Sat Oct 12 00:40:05 GMT (+0000) 2013
我什至通过调试器单步执行并看到了相同的结果 奇怪的结果:
stopped in main at line 27 in file "flight.c"
27 output_date ( day+1, month+1, year );
(dbx) print day+1, month+1, year
day+1 = 1
month+1 = 1
year = 1977
(dbx) step
stopped in output_date at line 43 in file "flight.c"
43 char buffer[64] = "";
(dbx) step
stopped in output_date at line 44 in file "flight.c"
44 struct tm *e_time = calloc( (size_t) 1, sizeof(struct tm) );
(dbx) step
stopped in output_date at line 46 in file "flight.c"
46 e_time->tm_year = year - 1900;
(dbx) print e_time
e_time = 0x100101640
(dbx) step
stopped in output_date at line 47 in file "flight.c"
47 e_time->tm_mon = month - 1;
(dbx) step
stopped in output_date at line 48 in file "flight.c"
48 e_time->tm_mday = day;
(dbx) step
stopped in output_date at line 49 in file "flight.c"
49 e_time->tm_hour = 0;
(dbx) step
stopped in output_date at line 50 in file "flight.c"
50 e_time->tm_min = 0;
(dbx) step
stopped in output_date at line 51 in file "flight.c"
51 e_time->tm_sec = 0;
(dbx) step
stopped in output_date at line 52 in file "flight.c"
52 e_time->tm_isdst = -1;
(dbx) step
stopped in output_date at line 55 in file "flight.c"
55 strftime ( buffer, 64, "%a %b %e %H:%M:%S %Z (%z) %Y", e_time );
(dbx) print *e_time
*e_time = {
tm_sec = 0
tm_min = 0
tm_hour = 0
tm_mday = 1
tm_mon = 0
tm_year = 77
tm_wday = 0
tm_yday = 0
tm_isdst = -1
}
(dbx) step
stopped in output_date at line 57 in file "flight.c"
57 printf ( "%s\n", buffer );
(dbx) print buffer
buffer = "Sun Jan 1 00:00:00 () 1977"
(dbx) quit
事实上,我所得到的只是一周中的某一天是星期天和正确的月份 正确的日期和年份。似乎没有什么是正确的。
我是否遗漏了一些明显的东西?
【问题讨论】:
-
什么编译器和操作系统?
-
到目前为止,我已经尝试了带有 gcc 4.7.2 的 Debian Linux 7.1 以及带有 Oracle Studio 12 的 Solaris 10。在 Solaris 上,我看到了上述结果。在 Linux 上,我得到一个段错误。抱歉..遇到了段错误...现在我得到了一个奇怪的结果。
-
它在 ideone.com 上也有段错误...
-
仅供参考...ideone.com/QpUguN 是对 ideone 的测试。另外,请查看 ideone 代码。无需像您在这里所做的那样致电
calloc和free。你在白白浪费时间。在e_time上调用memset足以避免段错误,但不会使输出完整。 -
只是想帮忙...`事实上,我可以在堆上使用一个普通变量。` %s/heap/stack/