Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are valid arguments for localtime function?

Tags:

c

I have a code here which uses localtime function. But for some values of its input argument, the code crashes (null pointer returned). I want to know about the allowable range for its input.

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

int main ()
{
  time_t rawtime;
  struct tm g;
  struct tm *gp;
  __int64 tim;

  tim = 7476811632013133299LL; // I know it's a weird number but valid for time_t
  rawtime = tim / 1000LL;
  gp = localtime(&rawtime);
  printf("Pointer gp = %p\n", gp);

  g = *gp; // this crahses because gp = NULL

  return 0;
}

So what can be said about the allowable range of input to localtime function?

like image 467
anupamb Avatar asked Jul 29 '26 01:07

anupamb


1 Answers

The allowable range is not specified by the C standard.

Quoting the N1570 draft:

The localtime function returns a pointer to the broken-down time, or a null pointer if the specified time cannot be converted to local time.

You should check whether the result is NULL before trying to dereference it.

like image 143
Keith Thompson Avatar answered Jul 30 '26 17:07

Keith Thompson



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!