Search code examples
cpointerstimedereference

how to check null pointer dereferencing when we have values instead of pointer


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


Solution

  • 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.