Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Explain what goes wrong with the third NCCE

...

Code Block
bgColor#FFCCCC
langc
jmp_buf buf;

void f(void) {
  int i = 0;
  if (setjmp(buf) != 0) {
    printf("%i\n", i);
    /* ... */
  }
  i = 2;
  g();
}

void g(void) {
  /* ... */
  longjmp(buf, 1);
}

Calling f() will print 2 if you compile with -O0, but will print 3 if you compile with -O2.

Compliant Solution

If an object local to the function that invoked setjmp() needs to be accessed after longjmp() returns control to the function, the object should be volatile-qualified:

Code Block
bgColor#ccccff
langc
jmp_buf buf;

void f(void) {
  volatile int i = 0;
  if (setjmp(buf) != 0) {
    printf("%i\n", i);
    /* ... */
  }
  i = 2;
  g();
}

void g(void) {
  /* ... */
  longjmp(buf, 1);
}

This will now correctly print 2 regardless of optimization level.

Risk Assessment

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MSC22-C

Low

Probable

Medium

P4

L3

...