从 Linux 移植到 OSX 时,时间和 ctime 出现段错误
我在 OSX 上编译为(我相信)Linux 设计的代码时遇到错误。我已将问题追查到这部分代码:
TIMEVAL = time(NULL);
char* TIMESTRING = ctime(&TIMEVAL);
TIMESTRING[24]=' ';
fprintf(LOG, "[ %20s] ", TIMESTRING);
是否有任何原因导致这种情况?我已经包含了
。
I am getting errors compiling code designed for (I believe) Linux on OSX. I have tracked down the issue to this section of code:
TIMEVAL = time(NULL);
char* TIMESTRING = ctime(&TIMEVAL);
TIMESTRING[24]=' ';
fprintf(LOG, "[ %20s] ", TIMESTRING);
Is there any reason why this might be the case? I have included <time.h>
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ctime
使用特定大小的静态分配的缓冲区,因此您的第一个问题是您在不知道大小的情况下附加到该字符串。如果缓冲区只有 24 字节,这可能会导致其自身出现段错误。另一个原因可能是,如果零终止恰好位于索引 24 处,则您刚刚使字符串未终止,并且 fprintf 将继续读取,直到它到达不允许读取的内存,从而导致段错误。
如果您想修改它,请将 ctime_r 与预分配的缓冲区一起使用,并确保缓冲区足够大以容纳您的数据,并且在完成后以零结尾。如果
ctime_r
不可用,请在修改之前对您自己的缓冲区执行strncpy
。HTH
编辑
我不确定你到底想做什么,但假设你发布的代码是直接从你的应用程序中获取的,你可能实际上想要这样做:
也就是说,pad你的时间字符串。只需在格式字符串中添加空格,而不是在时间字符串缓冲区中添加空格。
ctime
is using a statically allocated buffer of a certain size, so your first problem is that you're appending to that string without knowing the size.This might cause a segfault on it's own if the buffer is only 24 bytes. Another cause might be if the zero-termination happens to be at index 24, you just made the string unterminated, and
fprintf
will continue reading until it hits memory it's not allowed to read, resulting in the segfault.Use
ctime_r
with a preallocated buffer if you want to modify it, and make sure the buffer is large enough to hold your data, and is zero-terminated after you're done with it. Ifctime_r
isn't available, do astrncpy
to your own buffer before modifying.HTH
EDIT
I'm not sure exactly what you're trying to do, but assuming the code you posted is taken directly from your application, you're probably actually looking to do this:
That is, pad your time string. Just add the space in your formatting string instead of in the time-string buffer.
以此为例,ctime 返回 - Sat May 20 15:21:51 2010,只有 24 个字符(即 24 个字节)。因此,数组索引从 0 到 23 开始。因此,在索引 24 处它具有终止字符。
因此,
TIMESTRING[24]=' ';
是错误(即,您用空格字符替换终止字符),并导致您在稍后阶段出现分段错误。Taking this as an example what ctime returns - Sat May 20 15:21:51 2010 which is only 24 characters ( i.e., 24 bytes ). So, you array index start from 0 to 23. So, at index 24 it has termination character.
So,
TIMESTRING[24]=' ';
is wrong ( i.e., you are replacing the termination character with a space character ) and is causing you the segmentation fault at later stages.