【问题标题】:Do I need to free the returned pointer from localtime() function?我是否需要从 localtime() 函数中释放返回的指针?
【发布时间】:2016-01-27 07:57:30
【问题描述】:

我目前正在阅读有关time.h 的联机帮助页。我已经走到这一步了:

time_t now = time(0);
struct tm * local = localtime(&now);

现在我可以尽可能地利用时间,但我找不到有关free() 变量local 的责任与否的信息。

【问题讨论】:

    标签: c pointers time free


    【解决方案1】:

    引用man page

    四个函数asctime()ctime()gmtime()localtime()返回一个指向静态数据的指针,因此不是线程安全的。 [...]

    所以,你不需要free()返回的指针。

    【讨论】:

      【解决方案2】:

      查看了仿生库 c 代码中 localtime() 的实现 它的一些代码。 https://android.googlesource.com/platform/bionic/+/master/libc/tzcode/localtime.c

      static struct tm    tm;
      
      static struct tm *
      localtime_tzset(time_t const *timep, struct tm *tmp, bool setname)
      {
        int err = lock();
        if (err) {
          errno = err;
          return NULL;
        }
        if (setname || !lcl_is_set)
          tzset_unlocked();
        tmp = localsub(lclptr, timep, setname, tmp);
        unlock();
        return tmp;
      }
      struct tm *
      localtime(const time_t *timep)
      {
        return localtime_tzset(timep, &tm, true);
      }
      

      所以这里是静态结构tm的返回地址。

      所以我们不需要释放它。该系列的其他函数也访问该全局静态结构,因此它不是线程安全的。

      【讨论】:

        猜你喜欢
        • 2011-09-06
        • 1970-01-01
        • 2019-10-21
        • 1970-01-01
        • 2012-08-07
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 2013-10-20
        相关资源
        最近更新 更多