[ puzzle - printing time in human-readable form in C; ctime, asctime ]
there is a following puzzle to which I think I know the right answer but I have one issue as well. Have a look:
Sample Code
void printTime( time_t *t )
{
????
}
Which one of the following can replace the ???? in the code above to print the time passed in t in human-readable form?
:
char s[ 100 ]; ctime( t, s ); printf( "%s\n", s );
:
printf( "%s\n", ctime( t ) );
:
printf( "%s\n", asctime( t ) );
:
printf( "%s", t );
:
char *s = ctime( t ); printf( "%s\n", s ); free( s );
My answer is answer 2 (function ctime takes a time_t pointer as input and returns a pointer to a string which then can be printed by printf).
Code for answer 5 works as well when compiled but why would we use free() when no storage was previously allocated? Do you think that's why answer 5 is just wrong?
Thank you, Przemek
Answer 1
- Doesn't work this way, use
ctime_r
instead. - Works and is correct.
- Wrong type, you'd have to convert this first, e.g. using
localtime
. - Wrong variadic type,
char*
expected buttime_t*
given. - Incorrect free, as
ctime
manages its buffer itself, e.g. using a static one.
In general, most of these functions (i.e. asctime
, ctime
, localtime
, …) come in two variants these days: the historic form which uses some statically allocated buffer to hold the return value, and a more modern version with a _r
suffix which stands for reentrant. For the latter, you have to provide the output buffer yourself, which means you're responsible for allocating it. The great advantage is that multiple threads might use the reentrant versions simultaneously without fear of overwriting one another's results.