As you know the <time.h>
standard header defines the struct tm
and a function called localtime
.
Does localtime
make a heap allocation?
Or is it allocated in the stack?
It returns a pointer but this could be just a pointer to the stack value, right?
CodePudding user response:
localtime
returns a pointer to a global variable, it is shared between all threads:
Return value: pointer to a static internal
std::tm
object on success, or null pointer otherwise. The structure may be shared betweenstd::gmtime
,std::localtime
, andstd::ctime
, and may be overwritten on each invocation.
This function may not be thread-safe.
Modern applications should use localtime_r
instead of localtime
.
Example: glibc implementation of localtime
.
CodePudding user response:
localtime
returns a pointer to a static struct tm
object, ie: a global object that may or may not be thread local. The contents of this object can be overwritten by a subsequent call to this or another library function. It should not be accessed after the thread in which it the function was called as exited.
The object is not allocated from the heap, albeit an implementation that would allocate the object from the heap and handle its life cycle could still be conformant. You must not call free
with this pointer.
The object cannot be allocated with automatic storage as accessing it after the function localtime
returns would have undefined behavior.
You should use localtime_r
, a POSIX function that will be included in the next version of the C Standard:
#include <time.h>
struct tm *localtime_r(const time_t *timer, struct tm *buf);
localtime_r
takes a pointer to the destination object, which you can allocate as appropriate for your usage.
MSVC might not support this function, but you can define it on this target platform as a simple macro:
#ifdef _MSC_VER
#define localtime_r(a,b) localtime_s(a,b)
#endif