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. References#ISO/IEC 9899-1999]\]. Invoking {{setjmp()}} outside of one of these contexts results in undefined behavior (see [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 Undefined Behavior 121, 10).
The longjmp()
function should never be used to return control to a function that has terminated execution (see Undefined Behavior 120).
...
Noncompliant Code Example
The following This noncompliant code example calls setjmp()
in an assignment statement, resulting in undefined behavior.
...
Placing the call to setjmp()
in the if
statement and (optionally) comparing it with a constant integer removes the undefined behavior, as shown in this compliant solution.
Code Block | ||
---|---|---|
| ||
jmp_buf buf; void f() { if (setjmp(buf) == 0) { g(); } else { /* longjmp was invoked */ } } void g() { /* ... */ longjmp(buf, 1); } |
Noncompliant Code Example
Any attempt to invoke the longjmp()
function to transfer control to a function that has terminated completed execution results in undefined behavior.
Code Block | ||
---|---|---|
| ||
jmp_buf buf; void f() { g(); h(); return; } void g() { if (setjmp(buf) != 0) { /* longjmp was invoked*/ } return; } void h() { /* ... */ longjmp(buf, 1); } |
Compliant Solution
The longjmp()
function should only be used when the function containing the corresponding setjmp()
is guaranteed not to have terminated execution, as in the following example.
...