Skip to content
Advertisement

Maximum values for time_t (struct timespec)

I am using the struct timespec structure and here it is:

struct timespec {
           time_t tv_sec;                /* Seconds */
           long   tv_nsec;               /* Nanoseconds */
};

Thing is, user will be entering the values for each of these individual members, and i want to put a check a max. value the user can enter.

Can I take the max. value of time_t as int max value? i.e INT_MAX for tv_sec and LONG_MAX (defined in limits.h) for the tv_nsec? What will be the minimum acceptable values for both? Is it zero? I guess negative values can’t be accepted? Just to add, these values will be using in a timer.

P.S: Where is the typedef for time_t? Could not find it in time.h.

Advertisement

Answer

A time_t is simply a long int.
It’s defined in (on my Ubuntu linux system) /usr/include/time.h, however the definition stretches back all the way to /usr/include/bits/types.h, where __SLONGWORD_TYPE (which is what __TIME_T_TYPE is defined to) is defined.

The problem with simply checking if a value is greater than, say, LONG_MAX, is that once a value exceeds this value it will automatically wrap around and become negative. Thus you can’t check to see if anything is greater than this value – the macro is defined as the largest value this type can take.

You don’t really want a user to input these values – unless by ‘user’ you mean ‘developer’. The only real “safe” way to test this would be to let the user input a string (c-style, of course) and then run two checks:
1) Check to see if the user entered more digits than is allowed (a cheap trick is int(log10(number)) + 1 to count the amount of digits in a number).
2) If this is equal to the amount of digits, start comparing digit-by-digit. You can compare digit-by-digit by using a little bit of modulo arithmetic.

This is really the safest way to check whether or not the user inputs a number that’s far too large. You won’t run into any overflow issues this way, though it is terrifically tedious. Hope this helps.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement