[lug] localtime() returns pointer - free it?

Tkil tkil at scrye.com
Thu Nov 30 09:04:35 MST 2000


>>>>> "Michael" == Michael J Hammel <mjhammel at graphics-muse.org> writes: 

Michael> I noticed tonight that localtime() returns a pointer to a 
Michael> struct tm pointer.  Is the caller responsible for freeing the 
Michael> memory associated with that structure?   

it is usually a static extern that is returned, so (1) you don't need
to free it, (2) you don't *want* to free it, as that should cause your 
program to fall down and go boom, and (3) it's not thread-safe.

consider:

=============================================================================
#include <stdio.h>
#include <time.h>

int main()
{
  struct tm *a, *b;
  time_t t1;
  time_t t2;

  (void) time(&t1);
  t2 = t1+1;

  a = localtime(&t1);
  printf("a = 0x%p\n", a);
  
  b = localtime(&t2);
  printf("b = 0x%p\n", b);

  if (a == b)
  {
    printf("since they're the same, you don't need to `free' them.\n");
  }
  else
  {
    printf("since they're different, you DO need to `free' them.\n");
  }
}
=============================================================================

note that the two times are distinct, yet they return the same pointer.

Michael> Is the Linux behaviour (whether I need to free the space or 
Michael> not) consistant with other Unix platforms? 

so far as i know, this is a common response.  as i mentioned above,
this interface is not thread-safe; there might be alternatives that
*are* thread-safe, and those would probably have different interfaces
as well as probably adding the requirement that you provide the
structure to be filled in.

t.




More information about the LUG mailing list