Versions Compared

Key

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

Wiki Markup
The {{setjmp()}} macro should only be invoked from one of the contexts listed in §7.13.1.1 of \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\]. Invoking {{setjmp()}} outside of one of these contexts results in undefined behavior. (seeSee [Undefined Behavior 119|CC. Undefined Behavior#ub_119].).

After invoking longjmp(), non-volatile-qualified local objects should not be accessed if their values could have changed since the invocation of setjmp(). Their value in this case is considered indeterminate and accessing them is undefined behavior. (see See Undefined Behavior 121, 10.).
The longjmp() function should never be used to return control to a function that has terminated execution. (see See Undefined Behavior 120.).

Signal masks, floating-point status flags, and the state of open files are not saved by the setjmp() function. If signal masks need to be saved, the sigsetjmp() function should be used.

This recommendation is related to guidelines SIG32-C. Do not call longjmp() from inside a signal handler and ENV32-C. All atexit handlers must return normally.

...

The longjmp() function should only be used when the function containing the corresponding setjmp() is guaranteed not to have completed execution, as in the following example.:

Code Block
bgColor#ccccff
jmp_buf buf;
unsigned char b[] = {0xe5, 0x06, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00};

int main(void) {
  if (setjmp(buf) == 0) {
    printf("setjmp() invoked\n");
  } else {
    printf("longjmp() invoked\n");
  }
  do_stuff();
  return 0;
}

void do_stuff(void) {
  char a[8];
  memcpy(a, b, 8);
  /* ... stuff ... */
  longjmp(buf, 1);
}

void bad(void) {
  printf("Should not be called!\n");
  exit(1);
}

In this compliant solution, there is no risk of overwriting a return address because the stack frame of main() (the function that invoked setjmp()) is still on the stack, ; so when do_stuff() is invoked, the two stack frames will not overlap.

...