The C standard library facilities
longjmp() can be used to simulate throwing and catching exceptions. However, these facilities bypass automatic resource management and can result in undefined behavior, commonly including resource leaks and denial-of-service attacks.
The C++ Standard, [support.runtime], paragraph 4 [ISO/IEC 14882-2014], states the following:
The function signature
longjmp(jmp_buf jbuf, int val)has more restricted behavior in this International Standard. A
longjmpcall pair has undefined behavior if replacing the
throwwould invoke any non-trivial destructors for any automatic objects.
Do not call
longjmp(); their usage can be replaced by more standard idioms such as
throw expressions and
Noncompliant Code Example
throw expression would cause a nontrivial destructor to be invoked, then calling
longjmp() in the same context will result in undefined behavior. In the following noncompliant code example, the call to
longjmp() occurs in a context with a local
Counter object. Since this object’s destructor is nontrivial, undefined behavior results.
The above code produces the following results when compiled with Clang 3.8 for Linux, demonstrating that the program, on this platform, fails to destroy the local
Counter instance when the execution of
f() is terminated. This is permissible as the behavior is undefined.
This compliant solution replaces the calls to
longjmp() with a
throw expression and a
This solution produces the following output.
longjmp() could lead to a denial-of-service attack due to resources not being properly destroyed.
|Axivion Bauhaus Suite|
|Checked by |
|Use of longjmp|
Use of setjmp
|LDRA tool suite|
The setjmp macro and the longjmp function shall not be used
|Polyspace Bug Finder|
|CERT C++: ERR52-CPP||Checks for use of setjmp/longjmp (rule fully covered)|
|SonarQube C/C++ Plugin|
|[Henricson 1997]||Rule 13.3, Do not use |
|[ISO/IEC 14882-2014]||Subclause 18.10, "Other Runtime Support"|