Replace usage of std::ctime, which is not safe for use in multithreaded contexts

- std::ctime returns a pointer to a string that "may be shared between
  std::asctime and std::ctime, and may be overwritten on each invocation
  of any of those functions.".
  - https://en.cppreference.com/w/cpp/chrono/c/ctime
- Replaced with call to strftime to generate the same string
  representation (using the format string: %c)
- Leveraged localtime_r (which is thread-safe) to convert time_t to
  struct tm, as required by strftime.
This commit is contained in:
Eduardo Arias 2024-08-12 07:58:06 -07:00
parent 718d121ee3
commit 5e6fcbc60b

View File

@ -21,6 +21,11 @@
#include <utility>
#include <sstream>
#include <iomanip>
#include <time.h>
#ifdef WIN32
#include "src/compat/msvc.h"
#endif
#ifndef SRC_UTILS_STRING_H_
#define SRC_UTILS_STRING_H_
@ -60,9 +65,11 @@ const char HEX2DEC[256] = {
inline std::string ascTime(const time_t *t) {
std::string ts = std::ctime(t);
ts.pop_back();
return ts;
struct tm timeinfo;
localtime_r(t, &timeinfo);
char tstr[std::size("Www Mmm dd hh:mm:ss yyyy")];
strftime(tstr, std::size(tstr), "%c", &timeinfo);
return tstr;
}