0

The following code

{
    time_t t;
    t = time(NULL);
    char *A;
    A = ctime(&t);
    printf("%s -\n", A);
    sleep(2);
    time_t t1;
    t1 = time(NULL);
    printf("%s HERE A =\n", A);
    char *B = ctime(&t1);
    printf("%s HERE B =\n", B);
    printf("%s\n", B);
}

has output

Sat Mar 30 19:10:33 2019
 -
Sat Mar 30 19:10:33 2019
 HERE A =
Sat Mar 30 19:10:35 2019
 HERE B =
Sat Mar 30 19:10:35 2019

So how is variable A getting changed? what should I need to do so that A stays with fixed value

changing char *A; to const char *A; doesn't help

expected

Sat Mar 30 19:10:33 2019
 -
Sat Mar 30 19:10:33 2019
 HERE A =
Sat Mar 30 19:10:33 2019
 HERE B =
Sat Mar 30 19:10:35 2019
  • 1
    The [`ctime`](https://en.cppreference.com/w/c/chrono/ctime) function is not [reentrant](https://en.wikipedia.org/wiki/Reentrancy_(computing)). It only have a single buffer that it reuses. The pointer it returns is a pointer to the first character of this single buffer. – Some programmer dude Mar 30 '19 at 13:52

1 Answers1

1

So, ctime returns a pointer to a string. You're assigning that pointer to A and B. In this case, it's returning the same pointer, meaning A and B point to the same address in memory. You can see this if you add code to print the address:

printf("A=0x%x, B=0x%x", A, B);

The manual page for time explains that this is behavior to look out for:

The return value points to a statically allocated string which might be overwritten by subsequent calls to any of the date and time functions. The function also sets the external variables tzname, timezone, and daylight (see tzset(3)) with information about the current timezone. The reentrant version ctime_r() does the same, but stores the string in a user-supplied buffer which should have room for at least 26 bytes. It need not set tzname, timezone, and daylight.

So, to fix this, you can use the re-entrant version of ctime instead, ctime_r:

char C[27];
ctime_r(&t1, &C);

You could also use strcpy or strdup to copy it into your own string that won't get overwritten.

Here's another answer addressing that : Saving new points in time with ctime overwrites the old strings?

Tony Biondo
  • 173
  • 1
  • 9