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

962 views Asked by At

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>.

2

There are 2 answers

2
falstro On BEST ANSWER

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.

TIMESTRING[24]=' ';

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. If ctime_r isn't available, do a strncpy 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:

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.

4
Mahesh On

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.