2

The syntax for the gmtime function in the C Language is:

struct tm *gmtime(const time_t *timer);

usual call to gmtime would be

tm *xx = gmtime( &curr_time );

which would make it easier to check if NULL pointer was returned by gmtime function.

if (xx)
    return sucess;

however it is not safe as The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions.


so one of the safer approach would be to use

time_t curr_time = time(0);
tm xx = *gmtime( &curr_time );

but in case the if the call is made like this

how to check for null before dereferencing xx variable?

"not safe" source -- https://linux.die.net/man/3/gmtime

Himanshu Sourav
  • 700
  • 1
  • 10
  • 35

1 Answers1

6

Quoting from man-page

The gmtime() function converts the calendar time timep to broken-down time representation, expressed in Coordinated Universal Time (UTC). It may return NULL when the year does not fit into an integer. The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions. The gmtime_r() function does the same, but stores the data in a user-supplied struct.

So, you just have to do

time_t now = time(NULL);
struct tm result;

if (!gmtime_r(&now, &result)) {
  // error
}

Then, "result" can't be over-written by another time function call.

Tom's
  • 2,448
  • 10
  • 22
  • thanks, but gmtime_r() is undefined (why?? probably another question) – Himanshu Sourav Mar 13 '18 at 11:07
  • That because you don't have defined featured macro. From man page :Feature Test Macro Requirements for glibc (see feature_test_macros(7)): asctime_r(), ctime_r(), gmtime_r(), localtime_r(): _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _BSD_SOURCE || _SVID_SOURCE || _POSIX_SOURCE – Tom's Mar 13 '18 at 11:11
  • `gmtime_r()` is not standard C, although possible available to OP using other extended libraries. – chux - Reinstate Monica Mar 13 '18 at 11:55
  • 1
    Yes, but since he give a link to linux.die and not msdn, I assumed that is OS is Linux-like, and then give the thread safe function of gmtime for this case. For both windows / linux, there is this [answer](https://stackoverflow.com/questions/12044519/what-is-the-windows-equivalent-of-the-unix-function-gmtime-r) – Tom's Mar 13 '18 at 11:59
  • yes, the target system is linux based embedded system. – Himanshu Sourav Mar 13 '18 at 12:06
  • 1
    There are far more choices than just `linux and msdn. IAC, the post is not tagged Linux and so a Linux solution is a good guess but not a certainty. – chux - Reinstate Monica Mar 14 '18 at 06:19