我将pro * c代码从UNIX移植到Linux.代码被成功编译和创建可执行文件.但在运行时它的提升分段错误.我一步一步地调试了代码,下面是GDB调试的输出.
Breakpoint 4 at 0x3b19690f50
(gdb) n
525 strftime (buf, MAX_STRING_LEN, "%d/%b/%Y:%H:%M:%S", dummy_time);
(gdb) n
Breakpoint 4, 0x0000003b19690f50 in strftime () from /lib64/libc.so.6
(gdb) n
Single stepping until exit from function strftime,
which has no line number information.
0x0000003b19690f70 in strftime_l () from /lib64/libc.so.6
(gdb) n
Single stepping until exit from function strftime_l,
which has no line number information.
Program received signal SIGSEGV, Segmentation fault.
0x0000003b19690f8b in strftime_l () from /lib64/libc.so.6
实际上在代码中调用函数strftime().但我不知道为什么它会在/lib64/libc.so.6中到达strftime_l().
这个问题不会出现在UNIX中.请帮忙.代码是
static void speed_hack_libs(void)
{
time_t dummy_time_t = time(NULL);
struct tm *dummy_time = localtime (&dummy_time_t);
struct tm *other_dummy_time = gmtime (&dummy_time_t);
char buf[MAX_STRING_LEN];
strftime (buf, MAX_STRING_LEN, "%d/%b/%Y:%H:%M:%S", dummy_time);
}
struct tm *dummy_time = localtime (&dummy_time_t);
struct tm *other_dummy_time = gmtime (&dummy_time_t);
这不会奏效.从man page:
The localtime() function converts the calendar time timep to broken-down time representation, expressed relative to the user’s specified time-zone. … The return value points to a statically allocated struct which might be overwritten by
subsequent calls to any of the date and time functions.
The gmtime() function converts the calendar time timep to broken-down time representation, expressed in Coordinated Universal Time (UTC). It
may return NULL when the year does not fit into an integer. The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions.
因此,* dummy_time可能会在您使用它时被覆盖,并包含不可预测的垃圾.您应该将数据复制到缓冲区,如下所示:
struct tm dummy_time ;
memcpy(&dummy_time, localtime (&dummy_time_t), sizeof(struct tm));
虽然我不确定这怎么会导致SIGSEGV(可能是获得月份名称等等 – 检查问题是否仍然存在于LC_ALL = C),你必须先解决这个问题才能继续.另外,检查(在调试器中)* dummy_time的内容.