4

I have a question about how the glibc ctime() works.

Follows my snippet:

#include    <stdio.h>
#include    <time.h>
#include    <stdlib.h>


int main (int argc,char** argv)
{
    int ret=EXIT_SUCCESS;

    time_t tm1;
    time_t tm2;


    tm1 = time(NULL);
    tm2 = tm1 + 60; // 60 seconds later


    puts("1st method-------");
    printf("tm1 = %stm2 = %s",ctime(&tm1),ctime(&tm2));


    puts("2nd method-------");
        printf("tm1 = %s",ctime(&tm1));
    printf("tm2 = %s",ctime(&tm2));

    return(ret);
}

I got:

1st method-------
tm1 = Sat Jan 14 01:13:28 2012
tm2 = Sat Jan 14 01:13:28 2012
2nd method-------
tm1 = Sat Jan 14 01:13:28 2012
tm2 = Sat Jan 14 01:14:28 2012

As you see, in the first method both tm have the same value which is not correct. In the 2nd method I got correct values. I know that ctime() puts those string in static buffer, and to overwrite it we need a successive call to ctime().

Q: Do I not doing successive call in 1st method?

Thank you for reply.

hadibou
  • 328
  • 3
  • 8

1 Answers1

3

You've provided all the info necessary to solve the problem.

The second method works as you'd expect: ctime gets called, fills the buffer, and the results get printed; this process is then repeated. So you get the two distinct times printed.

For the first method, the order is different: ctime is called, then it is called again, and only then do the results get printed. The results from each call to ctime is the same, at least as far as printf is concerned: the address of the static buffer. But the contents of that buffer was changed by each call, and since printf doesn't look in the buffer until both ctime calls are done, it ends up printing the newer contents twice.

So you ARE making both calls in the first method, its just that the results of the first call get overwritten before they get printed.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • thank you, but as you see It kept the older (tm1) and not the newer (tm2) result, it doesn't overwrite the buffer, unless the ctime(&tm2) is processed before the ctime(&tm1) – hadibou Jan 14 '12 at 01:59
  • @Hadi: What you don't seem to understand is that arguments are pushed in reverse order. when both ctime statements are arugments to printf, the one with tm1 is called LAST, not FIRST. Scott got it right. – boatcoder Oct 12 '12 at 15:39
  • @Mark0978 Function parameters are not evaluated in a defined order in `C`. _You might have known it by this time._ http://stackoverflow.com/questions/376278/parameter-evaluation-order-before-a-function-calling-in-c – VoidPointer Jul 11 '13 at 14:46
  • @VoidPointer Good point. I've never encountered any implementation that didn't do it that way though. – boatcoder Jul 12 '13 at 17:15
  • 1
    to make successive calls, there are ctime_r function for unix and ctime_s function for windows. (for your interest) – anilbey Sep 03 '14 at 16:09