当我们有值而不是指针时如何检查空指针取消引用

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

C 语言中 gmtime 函数的语法是:

struct tm *gmtime(const time_t *timer);

通常调用 gmtime 是

tm *xx = gmtime( &curr_time );

这样可以更容易地检查 NULL 指针是否被 gmtime 函数return编辑。

if (xx)
    return sucess;

但是它并不安全,因为 return 值指向一个静态分配的结构,该结构可能会被后续调用任何日期和时间函数覆盖。


所以更安全的方法之一是使用

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

但万一调用是这样的

如何在取消引用 xx 变量之前检查空值?

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

引用自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.

所以,您只需要做

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

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

那么,"result"就不能over-written被其他时间函数调用了。