C中localtime的结果结构是如何分配的? [英] How is the result struct of localtime allocated in C?

查看:14
本文介绍了C中localtime的结果结构是如何分配的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C 语言中的 time.h 文件来帮助我们处理时间/日期函数.

我遇到了:

struct tm * _Cdecl localtime(const time_t *__timer);

...它似乎返回一个指向 tm 结构的指针.我发现按地址返回主要用于返回新的内存分配.

如果是这样,上面的返回实际上是如何工作的(struct tm 的返回地址).返回的对象是否在某处定义?

谢谢

解决方案

localtime(和其他一些函数)返回的指针实际上是指向静态分配内存的指针.所以你不需要释放它,也不应该释放它.

http://www.cplusplus.com/reference/clibrary/ctime/当地时间/

<块引用>

这个结构是由函数静态分配和共享的gmtime 和本地时间.每次这些功能之一是调用这个结构的内容被覆盖.

添加评论中提到的一些内容.

这种共享数据结构的直接结果是 localtime 和类似的函数不是线程安全的.线程安全的解决方案因平台而异.localtime_r for POSIXlocaltime_s for MSVC.

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 *__timer);

...which seems to return a pointer to tm struct. I have found that return by address is mostly used to return new memory allocations.

If this is so, how does the above return actually work (the return address of a struct tm). Is the returned object defined somewhere?

Thanks

解决方案

The pointer returned by localtime (and some other functions) are actually pointers to statically allocated memory. So you do not need to free it, and 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.

这篇关于C中localtime的结果结构是如何分配的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆