The type time_t
is specified as an "arithmetic type capable of representing times." However, how the way time is encoded within this arithmetic type by the function time()
is unspecified. See unspecified behavior 43 48 in section Annex J .1 of C99the C Standard. 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.
...
This noncompliant code example attempts to execute do_work()
multiple times until at least seconds_to_work
has passed. However, because the encoding is not defined, there is no guarantee that adding start
to seconds_to_work
will result in adding seconds_to_work
seconds.
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 may still might not exit , because the range of time_t
may might not be able to represent two times seconds_to_work
apart.
...
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC05-C | low Low | unlikely Unlikely | medium Medium | P2 | L3 |
Automated Detection
Tool | Version | Checker | Description |
---|---|---|---|
Compass/ROSE |
...
|
| Can detect violations of this recommendation | |||||||
| CC2.MSC05 | Fully implemented | |||||||
LDRA tool suite |
| 96 S, 101 S, 107 S, 433 S, 458 S | Partially Implemented |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
...
Related Guidelines
...
...
...
References
...
Bibliography
[Kettlewell 2002] | Section |
...
4.1, |
...
"time_t " |
...
\[[ISO/IEC 9899:1999|AA. References#ISO/IEC 9899-1999]\] Section 7.23, "Date and time <time.h>" 49. Miscellaneous (MSC) MSC06-C. Be aware of compiler optimization when dealing with sensitive data