简体   繁体   English

从Linux移植到OSX时,时间和ctime出现段错误

[英]Seg fault with time and ctime, when porting from Linux to OSX

I am getting errors compiling code designed for (I believe) Linux on OSX. 我在编译专为OSX上的Linux设计的代码时遇到错误。 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> . 我包括了<time.h>

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. ctime使用的是一定大小的静态分配的缓冲区,因此您的第一个问题是要在不知道大小的情况下追加到该字符串。

TIMESTRING[24]=' ';

This might cause a segfault on it's own if the buffer is only 24 bytes. 如果缓冲区只有24个字节,这可能会导致段错误。 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. 另一个原因可能是,如果零终止恰好在索引24处,则您只是使字符串终止了, fprintf将继续读取,直到它到达不允许读取的内存为止,从而导致段错误。

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. 如果要修改ctime_r ,请与预分配的缓冲区一起使用,并确保该缓冲区足够大以容纳数据,并且在使用ctime_r该缓冲区以0结尾。 If ctime_r isn't available, do a strncpy to your own buffer before modifying. 如果ctime_r不可用,请在修改之前对自己的缓冲区执行strncpy

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: 我不确定您要做什么,但是假设您发布的代码直接从您的应用程序中获取,您实际上可能正在寻找这样做:

TIMEVAL = time(NULL);
char* TIMESTRING = ctime(&TIMEVAL);

fprintf(LOG, "[ %20s ] ", TIMESTRING);

That is, pad your time string. 也就是说,填充您的时间字符串。 Just add the space in your formatting string instead of in the time-string buffer. 只需在格式字符串中添加空格,而不要在时间字符串缓冲区中添加空格。

Taking this as an example what ctime returns - Sat May 20 15:21:51 2010 which is only 24 characters ( ie, 24 bytes ). 以这个为例,ctime返回的结果- 2010年5月20日星期六15:21:51 ,它只有24个字符(即24个字节)。 So, you array index start from 0 to 23 . 因此,数组索引从0到23开始。 So, at index 24 it has termination character. 因此,在索引24处具有终止字符。

So, TIMESTRING[24]=' '; 因此, TIMESTRING[24]=' '; is wrong ( ie, you are replacing the termination character with a space character ) and is causing you the segmentation fault at later stages. 错误的 (即,您将终止字符替换为空格字符),并在以后导致分段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM