简体   繁体   中英

Do I need to free the returned pointer from localtime() function?

I am currently reading the manpages about time.h . I got this far:

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

Now I can work with the time, as far as good, but I do not find the information if its my duty to free() the variable local or not.

Quoting the man page

The four functions asctime() , ctime() , gmtime() and localtime() return a pointer to static data and hence are not thread-safe. [...]

So, you need not free() the returned pointer.

Looked in implementation of localtime() in bionic lib c code Some code from it. 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);
}

SO here it return address of static structure tm.

So we do not need to free it. And other function of that family also access that global static structure so its not thread safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM