How is the result struct of localtime allocated in C?
我在玩C语言中的
我遇到了:
1 |
…它似乎返回一个指向tm结构的指针。我发现按地址返回主要用于返回新的内存分配。
如果是这样,上面的返回实际上是如何工作的(
谢谢
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.
号
编辑:附加评论中提到的一些内容。
这种共享数据结构的直接结果是
它返回一个指向静态分配内存的指针(可能是在
显然,这个函数是不可重入的(但如果使用了tls,则可以是线程安全的)。
使用此指针时必须小心:不要进行任何可以调用
一般来说,日期/时间库的设计已经过时了,这种优化在C语言的设计中是有价值的,而现在它只给出了一些问题。
为了解决这些问题,这些函数至少有两个不同的改进版本:
手册上写着:
The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions.
号
也:
The localtime_r() function does the same, but stores the data in a user-supplied struct. It need not set tzname, timezone, and daylight.
号
它们返回指向库本地静态结构的指针。从手册页:
1 2 3 4 5 6 7 8 9 10 11 12 13 | NOTES The four functions asctime(), ctime(), gmtime() and localtime() return a pointer to static data and hence are not thread-safe. Thread-safe versions asctime_r(), ctime_r(), gmtime_r() and localtime_r() are spec‐ ified by SUSv2, and available since libc 5.2.5. POSIX.1-2001 says:"The asctime(), ctime(), gmtime(), and localtime() functions shall return values in one of two static objects: a broken- down time structure and an array of type char. Execution of any of the functions may overwrite the information returned in either of these objects by any of the other functions." This can occur in the glibc implementation. |
号
实际上,
1 2 3 4 5 6 7 8 9 |
由