Next: ctime_r
, Previous: ctermid
, Up: ISO C and POSIX Function Substitutes [Contents][Index]
ctime
POSIX specification:
https://pubs.opengroup.org/onlinepubs/9699919799/functions/ctime.html
Gnulib module: ctime
Portability problems fixed by Gnulib:
TZ
has been set by Cygwin.
Portability problems not fixed by Gnulib:
localtime_r
and strftime
(or even sprintf
) instead.
However, localtime_r
can fail and strftime
is locale dependent.
INT_MIN
+1900 or after the
year INT_MAX
+1900.
ctime
function need not be reentrant, and consequently is
not required to be thread safe. Implementations of ctime
typically write the timestamp into static buffer. If two threads
call ctime
at roughly the same time, you might end up with the
wrong date in one of the threads, or some undefined string.
tzset
.
Although ctime
and related functions asctime
, asctime_r
and ctime_r
formerly were plausible to use,
they are now unsafe in general, and should be avoided.
Decades ago when time_t
was narrow
and there was no strftime
or internationalization,
code could call these functions and then select the parts needed.
For example, in Unix 7th Edition /usr/src/cmd/ls.c (1979):
cp = ctime(&p->lmtime); if(p->lmtime < year) printf(" %-7.7s %-4.4s ", cp+4, cp+20); else printf(" %-12.12s ", cp+4);
This had well-defined behavior when time_t
was only 32 bits
and so was OK for circa 1979 platforms.
However, today’s platforms have a time_t
so wide
that the year might not be in the range [1000, 9999].
In this case the behavior of ctime
is undefined
and some platforms behave badly, overrunning a buffer
or dereferencing an internal null pointer;
and even on platforms where no undefined behavior occurs,
the 7th Edition code generates wrong output for out-of-range years,
because it incorrectly assumes that every year is represented by
exactly four digits.
Next: ctime_r
, Previous: ctermid
, Up: ISO C and POSIX Function Substitutes [Contents][Index]