hadibou
hadibou

Reputation: 338

Understand successive call to ctime()

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.

Upvotes: 4

Views: 459

Answers (1)

Scott Hunter
Scott Hunter

Reputation: 49920

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.

Upvotes: 3

Related Questions