Question

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?

  1. :

    char s[ 100 ];
    ctime( t, s ); 
    printf( "%s\n", s ); 
    
  2. :

    printf( "%s\n", ctime( t ) ); 
    
  3. :

    printf( "%s\n", asctime( t ) ); 
    
  4. :

    printf( "%s", t ); 
    
  5. :

    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

Was it helpful?

Solution

  1. Doesn't work this way, use ctime_r instead.
  2. Works and is correct.
  3. Wrong type, you'd have to convert this first, e.g. using localtime.
  4. Wrong variadic type, char* expected but time_t* given.
  5. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top