C 函数 returns 指向结构的指针

C function returns pointer to a struct

我开始学习 Linux C 编程,我遇到了以下情况:

time_t now;
struct tm *local_time;

now = time(NULL);
local_time = localtime(&now);

函数 localtime,它是 Linux API 的一部分,接受一个指向 time_t 的指针,这很好,但为什么它 return 指向 tm 结构的指针?

我的问题是 tm 结构在初始化后如何管理?

如果 localtime 静态分配结构,它不能保证结构不会随着程序的进行而被覆盖,如果 tm 结构是动态分配的,那么程序员必须调用 free 不再需要该结构。

那么 return 指针的 C 函数的正确阶段是什么?

谢谢!

根据 manpage for localtime(为清楚起见添加了粗体和斜体):

The localtime() function converts the calendar time timep to broken-down time representation, expressed relative to the user's specified timezone. The function acts as if it called tzset(3) and sets the external variables tzname with information about the current timezone, timezone with the difference between Coordinated Universal Time (UTC) and local standard time in seconds, and daylight to a nonzero value if daylight savings time rules apply during some part of the year. 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.

粗体部分表示 return 值的行为与您猜测的完全相同,后续调用可能会覆盖先前的 returned 结构。

您要么需要立即缓存结果结构,要么使用斜体部分提到的函数。

凯文解释了问题所在,您的假设是正确的。 对于这样的 类 函数,您可以应用简单的修复:

time_t now;
struct tm local_time;

now = time(NULL);
local_time = *localtime(&now);

在 return 从 localtime(&now) 开始,静态分配结构的内容将被复制到本地结构 local_time

编辑:还有很多其他话要说:

  1. 您在使用线程间函数时仍然遇到问题...
  2. 在许多实现中,mktimegmtime 共享同一个缓冲区,因此使用它们也可以修改结构。
  3. C99 和 C11 提供更安全的功能 [TR 24731-1]。

    localtime_s(const time_t * restrict timer, struct tm * restrict dst);