Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 493
Nidhoegger Avatar asked Oct 25 '25 06:10

Nidhoegger


2 Answers

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.

like image 196
Sourav Ghosh Avatar answered Oct 26 '25 21:10

Sourav Ghosh


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.

like image 31
Jeegar Patel Avatar answered Oct 26 '25 20:10

Jeegar Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!