The type time_t
is specified as an "arithmetic type capable of representing times." However, how time is encoded within this arithmetic type by the function time()
is unspecified. See unspecified behavior 43 46 in section J.1 of guideline C99the C Standard [ISO/IEC 9899:2011]. Because the encoding is unspecified, there is no safe way to manually perform arithmetic on the type, and , as a result, the values should not be modified directly.
Note that POSIX ® specifies that the time()
function must return a value of type time_t
, representing time in seconds since the Epoch. Thus, POSIX-conforming applications that aren't are not intended to be portable to other environments therefore may safely perform arithmetic operations on time_t
objects.
...
Code Block | ||||
---|---|---|---|---|
| ||||
int do_work(int seconds_to_work) {
time_t start = time(NULL);
if (start == (time_t)(-1)) {
/* Handle error */
}
while (time(NULL) < start + seconds_to_work) {
/* ... */
}
return 0;
}
|
...
This compliant solution uses difftime()
to determine the difference between two time_t
values. The difftime()
function returns the number of seconds, from the second parameter until the first parameter and result, as a double
.
Code Block | ||||
---|---|---|---|---|
| ||||
int do_work(int seconds_to_work) {
time_t start = time(NULL);
time_t current = start;
if (start == (time_t)(-1)) {
/* Handle error */
}
while (difftime(current, start) < seconds_to_work) {
current = time(NULL);
if (current == (time_t)(-1)) {
/* Handle error */
}
/* ... */
}
return 0;
}
|
Note that this loop still might still not exit because the range of time_t
might not be able to represent two times seconds_to_work
apart.
...
Tool | Version | Checker | Description | section|
---|---|---|---|---|
Compass/ROSE |
|
| Section | Can detect violations of this recommendation. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
CERT C++ Secure Coding Standard: MSC05-CPP. Do not manipulate time_t typed values directly
ISO/IEC 9899:1999 Section 2011 Section 7.2327, "Date and time <time.h>
"
Bibliography
[Kettlewell 2002] Section 4.1, "time_t"
...