c - Seg fault with time and ctime, when porting from Linux to OSX -
i getting errors compiling code designed (i believe) linux on osx. have tracked down issue section of code:
timeval = time(null); char* timestring = ctime(&timeval); timestring[24]=' '; fprintf(log, "[ %20s] ", timestring);
is there reason why might case? have included <time.h>
.
ctime
using statically allocated buffer of size, first problem you're appending string without knowing size.
timestring[24]=' ';
this might cause segfault on it's own if buffer 24 bytes. cause might if zero-termination happens @ index 24, made string unterminated, , fprintf
continue reading until hits memory it's not allowed read, resulting in segfault.
use ctime_r
preallocated buffer if want modify it, , make sure buffer large enough hold data, , zero-terminated after you're done it. if ctime_r
isn't available, strncpy
own buffer before modifying.
hth
edit
i'm not sure you're trying do, assuming code posted taken directly application, you're looking this:
timeval = time(null); char* timestring = ctime(&timeval); fprintf(log, "[ %20s ] ", timestring);
that is, pad time string. add space in formatting string instead of in time-string buffer.
Comments
Post a Comment