You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 15 Next »

The type, precision, and range of clock_t are implementation defined. time_t is specified as an "arithmetic type capable of representing times"as size_t, which is "an unsigned integer type", but how time is encoding within the arithmetic type is unspecified.

Computing Time Passed

Non-Compliant Code Example

This code attempts to execute do_some_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 adding seconds_to_work seconds.

int do_work(int seconds_to_work) {
  time_t start;
  start = time();
  if (start == (time_t)(-1)) {
    /* Handle error */
  }
  while (time() < start + second_to_work) {
    do_some_work();
  }
}

Compliant Code Example

The compliant code example uses difftime() to determine the difference between two time_t values. difftime() returns the number of seconds from the second parameter until the first parameter and returns the result as a double.

int do_work(int seconds_to_work) {
  time_t start, current;
  start = time();
  if (start == (time_t)(-1)) {
    /* Handle error */
  }
  while (time() < start + second_to_work) {
    current = time();
    if (current == (time_t)(-1)) {
       /* Handle error */
    }
    if (difftime(current, start) >= seconds_to_work)
      break;
    do_some_work();
  }
}

Note that this loop may still not exit, as the range of time_t may not be able to represent two times seconds_to_work apart.

Compute time in the future or past

This section is incomplete

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC05-A

5

2

2

P6

L2


References

- The original idea for this came from the C Language Gotchas site, accessible here

- The wikipedia article on Unix Time is quite enlightening. Read it here

- An article about a denial-of-service in 64bit microsoft time code. Read it here 

- Interesting time_t discussion from which I pulled my example code. Read it here

  • No labels