Localtime是否返回分配的TM*
如您所知,< time.h>
标准标头定义 struct tm
和称为 localtime
的函数。
localtime
做出堆分配吗?
还是在堆栈中分配?
它返回指针,但这可能只是指向堆栈值的指针,对吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C标准(C18)的相关部分具有以下语言:
localtime
返回静态struct tm
对象的指针,即:一个可能是线程本地线程的全局对象。该对象的内容可以被随后呼叫或其他库函数覆盖。将其称为函数的线程退出后,不应访问它。该对象不是从堆中分配的,您不得用此指针调用
免费
。在函数
localtime
返回之后访问它的行为将不确定,因此无法将对象分配给自动存储。您应该使用
localtime_r
,而不是localtime
,它将包含在C标准的下一个版本中(C23)(C23):localtime_r
将指针指向目标对象,您可以定义或分配适合使用。MSVC可能不支持此功能,但是您可以将其定义为一个简单的宏:
The relevant part of the C Standard (C18) has this language:
localtime
returns a pointer to a staticstruct 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 has exited.The object is not allocated from the heap, 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.Instead of
localtime
, you should uselocaltime_r
, a POSIX function that will be included in the next version of the C Standard (C23):localtime_r
takes a pointer to the destination object, which you can define or allocate as appropriate for your usage.MSVC might not support this function, but you can define it on its target platforms as a simple macro:
localtime
将指针返回到全局可变,通常在所有线程之间共享:现代应用程序应使用
localtime_r
而不是localtime
。示例: localtime 。
localtime
returns a pointer to a global variable, it is often shared between all threads:Modern applications should use
localtime_r
instead oflocaltime
.Example: glibc implementation of
localtime
.