Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Non-Compliant Coding Example

If the value of i is cached, the while loop may never terminate. When compiled on gcc with the -O optimization flag, the program fails to terminate even upon receiving a SIGINTThe following non-compliant code relies on the reception of a SIGINT signal to toggle a flag to terminate a loop.

Code Block
bgColor#ffcccc


#include <signal.h>

sig_atomic_t i;

void handler(int signum) {
  i = 0;
}

int main(void) {
  i = 1;
  signal(SIGINT, handler);
  while (i) {
   /* do something */
  }
  return 0;
}

However, if the value of i is cached, the while loop may never terminate. When compiled on GCC with the -O optimization flag, the program fails to terminate even upon receiving a SIGINT.

Non-Compliant Coding Example

The following non-compliant code prevents the compiler from optimizing away the loop condition, by typecasting the variable to volatile within the while loop.

...

The sig_atomic_t type is the integer type of an object that can be accessed as an atomic entity, even in the presence of asynchronous interrupts. The type of sig_atomic_t is implementation-defined, although there are constraints. Only assign integer though it has some guarantees. Integer values from 0 through 127 can be safely stored to a variable of type sig_atomic_t to be fully portable (see SIG31-C. Do not access or modify shared objects in signal handlers) safely.

Risk Assessment

Failing to use the volatile qualifier can result in race conditions in asynchronous portions of the code, causing unexpected values to be stored and leading to possible data integrity violations.

...