How is the result struct of localtime allocated in C?

后端 未结 6 1073
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 04:47

I was playing with the time.h file in C that helps us with time/day functions.

I came across:

struct tm * _Cdecl localtime(const time_t          


        
6条回答
  •  误落风尘
    2020-11-30 05:15

    The pointer returned by localtime (and some other functions) are actually pointers to statically allocated memory. So you do not need to freed. Furthermore, you should not free it.

    http://www.cplusplus.com/reference/clibrary/ctime/localtime/

    This structure is statically allocated and shared by the functions gmtime and localtime. Each time either one of these functions is called the content of this structure is overwritten.

    EDIT : Appending a few things mentioned in the comments.

    A direct result of this shared data-structure is that localtime and similar functions are not thread-safe. The thread-safe solution varies with different platforms. localtime_r for POSIX and localtime_s for MSVC.

提交回复
热议问题