Search code examples
ctimesegmentation-faultctime

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


Solution

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