cstandards

Are `asctime_r` and `ctime_r` standard in C?


As we already know, asctime and ctime are not thread-safe since they return a pointer of the internal static variables, cppreference only list the alternatives asctime_s and ctime_s which receive input buffers so they're thread-safe.

But _s functions is in "Annex K" of the C language standard, which is optional. GCC/Clang chose not to implement them because bounds-checked interfaces are still controversial.

I can find other functions with _r endings at cppreference, such as localtime_r is available since C23, but I can't find asctime_r or ctime_r, and Google only gives results for it from the Linux documentation. Although they are available on GCC/Clang.

Are they C standard? If not, do we currently have a cross-platform thread-safe usable version to replace them (besides other functions like strftime)?


Solution

  • Note that strftime is recommended instead all asctime_r and ctime_r and ctime and asctime functions. See https://man.archlinux.org/man/ctime.3.en#HISTORY , https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2566.pdf .

    Are asctime_r and ctime_r standard in C?

    No.

    They were considered and removed following input from The Austin Group https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2528.pdf .

    They were part of POSIX since 1988 and removed in POSIX.1-2024. It is the bug report https://austingroupbugs.net/view.php?id=1410 .

    Note that ctime and asctime functions are obsolescent both in standard C23 and in POSIX.1-2008.

    do we currently have a cross-platform thread-safe usable version to replace them (besides other functions like strftime)?

    The let's say reference implementation for anything time related is the tz library. It comes with asctime_r and ctime_r functions. https://github.com/eggert/tz/blob/main/asctime.c#L66