我正在玩 C 语言的 time.h
文件,它可以帮助我们处理时间/日期函数。
我遇到了:
struct tm * _Cdecl localtime(const time_t *__timer);
...这似乎返回一个指向 tm 结构的指针。我发现按地址返回主要用于返回新的内存分配。
如果是这样,那么上面的返回实际上是如何工作的(struct tm
的返回地址)。返回的对象是否在某处定义?
谢谢
最佳答案
localtime
(以及其他一些函数)返回的指针实际上是指向静态分配内存的指针。 所以你不需要释放它,也不应该释放它。
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.
编辑:附加评论中提到的一些内容。
这种共享数据结构的直接结果是 localtime
和类似的函数不是线程安全的。线程安全的解决方案因平台而异。 localtime_r
for POSIX和 localtime_s
for MSVC .
关于c - localtime 的结果结构如何在 C 中分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8694365/