ctimeposix

Can time(NULL) ever return failure?


Can the time_t time(time_t *t) function ever return failure if the argument passed is always NULL?

If the call is time(NULL), do we still need to check for the return value?

The only documented error code is EFAULT, which relates to the pointer being invalid.


Solution

  • Yes. time has a documented may fail case:

    The time() function may fail if:

    [EOVERFLOW] The number of seconds since the Epoch will not fit in an object of type time_t.

    Source: http://pubs.opengroup.org/onlinepubs/9699919799/functions/time.html

    Expect this to happen in practice in about 22 years, no sooner, and not on 64-bit systems or 32-bit ones that utilize a 64-bit time_t.

    Also, the presence of any shall fail or may fail cases also allows for implementation-defined errors, though their existence would be a serious quality-of-implementation flaw.

    EFAULT is a non-issue/non-existent because it only happens when your program has undefined behavior.

    So despite all this, in the real world, time is not actually going to fail.