Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 135 ยท Advanced C

setjmp and longjmp

Learn how setjmp and longjmp jump out of deeply nested C calls, build exception-like error recovery, and why leaks, volatile locals and dead frames make them risky.

A return statement leaves one function and goes back to its caller. A goto can jump around inside one function. But what if you are five calls deep in a parser, find a fatal error, and want to get all the way back to the top? You could check a return value after every call and pass errors upward by hand, which is the normal C approach (see Error Handling). C also has a blunt tool for this situation: setjmp and longjmp from <setjmp.h>, a non-local jump that unwinds many stack frames at once.

C has no exceptions, and this pair is the closest thing the standard library offers. It is powerful, easy to misuse, and worth understanding even if you rarely write it, because real libraries (some image decoders, interpreters, test frameworks) use it internally.

The basic idea

setjmp(env) saves the current execution context (the stack pointer, the program counter and some registers) in a jmp_buf object, then returns 0. Later, longjmp(env, value) restores that context. Execution then continues as if the original setjmp call had just returned a second time, but this time with the non-zero value you passed.

sequenceDiagram
    participant M as main
    participant A as parse()
    participant B as read_number()
    M->>M: setjmp(env) returns 0
    M->>A: call parse()
    A->>B: call read_number()
    B->>M: longjmp(env, 1)
    Note over M: setjmp returns 1 again,<br/>parse and read_number frames are gone

longjmp skips every frame in between and resumes at the setjmp call, which now returns the value you chose.

Because setjmp returns twice (once directly, once after a longjmp), you always call it inside an if or switch and branch on the result:

C Escaping from nested calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The level4, level3 and level2 frames all vanish at once. The "not printed" lines never run, because the frames that would have printed them no longer exist.

A few rules about the arguments:

  • If you pass 0 as value to longjmp, setjmp returns 1 instead, so the two cases can always be told apart.
  • jmp_buf is an array type, so passing it to a function passes a pointer to it, and longjmp(env, 1) needs no &.
  • longjmp never returns to its caller.

Using it for error recovery

A common pattern is a "try" region: set a jump target before running risky code, then call longjmp from deep inside when something goes wrong. Wrapping it in a small structure keeps nested regions manageable.

C A tiny try/catch built from setjmp

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

try_evaluate saves the previous handler and restores it when it finishes, so a function that uses try_evaluate inside its own try region would still work. Every path through the switch reaches the restore line. That is deliberate: if a region were left without restoring current_handler, it would point at a dead stack frame.

Note: Using setjmp directly as a switch controlling expression, as above, is one of the few forms the standard allows. The standard permits setjmp only in a few simple contexts: the entire controlling expression of if, switch, while, for; compared with an integer constant; as the operand of !; or as a plain expression statement. Storing the result in a variable (int code = setjmp(env);) is not strictly in that list, although every mainstream compiler accepts it. The safest style is the if/switch form.

Danger 1: the frame must still exist

longjmp can only jump to a setjmp whose function has not returned yet. If that function has already returned, its stack frame is gone and the saved context points at memory that now belongs to other calls. Jumping there is undefined behavior; the program may crash, loop or do something even stranger.

C
static jmp_buf saved;

static void remember(void)
{
    if (setjmp(saved) == 0) {
        return;                 /* the frame ends here */
    }
    puts("never do this");
}
/* later: remember(); longjmp(saved, 1);   <-- undefined behavior */

longjmp is a "jump back up the call chain" tool, never "jump to a function that finished" or "jump sideways to another thread". Jumping into a different thread's jmp_buf is also undefined.

Danger 2: locals can have the wrong value

When longjmp restores registers, a local variable that lives in a register may be restored to the value it had at setjmp time instead of the value it had just before the jump. The standard says: local variables that are not volatile and were changed between setjmp and longjmp have indeterminate values afterwards. Optimization decides whether it actually bites, so a program can pass at -O0 and fail at -O2.

The fix is to declare such variables volatile (see volatile and C11 Atomics), which forces the compiler to keep them in memory:

C volatile keeps a local reliable across longjmp

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Without volatile, reading attempts in the else branch is not guaranteed to give 3. Modern code that avoids this problem simply doesn't modify locals between the two calls, or keeps the state in file-scope or heap objects instead of locals of the setjmp function.

Danger 3: nothing is cleaned up

longjmp is not like a C++ exception: no destructors, no cleanup code. Every function between the jump and the target is simply abandoned, along with anything it owned:

  • Memory from malloc is never freed, so it leaks.
  • Open files are never closed, and buffered output may never be flushed.
  • Locks stay locked.
  • Any partly updated data structure stays partly updated.
flowchart TD
    A["parse() allocates buffer"] --> B["helper() runs"]
    B --> C["longjmp(env, 1)"]
    C --> D["main resumes after setjmp"]
    A -.-> E["buffer is never freed<br/>(leak)"]

Frames between the jump and the target are discarded without running any of their cleanup code.

The standard way to cope is to keep ownership information somewhere the handler can find it: keep an explicit list of resources, or allocate everything from one arena that the recovery code frees in one call.

C Cleaning up after a longjmp

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

res is a file-scope variable, not a local of the function that called setjmp, so the rule about indeterminate locals doesn't apply and the recovery code reliably sees what must be released. Try moving res into main and passing its address to work: with optimization on, the compiler may assume the buffer pointer is still NULL after the jump and skip the cleanup. That is the previous danger in action.

Signals and sigsetjmp

Old Unix code often jumped out of a signal handler with longjmp. This works only with care: setjmp may or may not save the signal mask, which is system dependent. POSIX therefore adds sigsetjmp(env, 1) and siglongjmp(env, value), where the second argument asks to save and restore the signal mask. Use those variants if you jump out of a handler (see Signals). Jumping out of a handler is also only safe if the signal did not interrupt a non-reentrant function such as malloc or printf.

When to use it, and when not to

Situation Better choice
Normal error handling in application code Return codes, errno and cleanup with goto
Releasing resources on several error paths A goto cleanup; label (see break, continue and goto)
Abandoning a deeply nested parser or decoder, with a single owner of memory setjmp/longjmp can be reasonable
Coroutines or cooperative threads Use the platform's context APIs; plain longjmp into a returned frame is undefined
Portable error handling across threads Not possible; jmp_buf is per thread

The simplest rule: if a normal return can express the error path, use it. Reach for longjmp only when you have measured that threading error codes through many levels is truly worse, and when you can account for every resource the skipped frames owned.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does setjmp return the FIRST time it is called?

    setjmp returns 0 when it saves the context. It returns a non-zero value only when it is "returned to" a second time through longjmp.
  2. 2. What does longjmp(env, 0) cause setjmp to return?

    The standard says that passing 0 makes setjmp return 1, so the code after a jump can always be told apart from the initial call.
  3. 3. A function calls setjmp(saved), stores the jmp_buf in a global and returns. Later, another function calls longjmp(saved, 1). What happens?

    longjmp is only valid while the function that called setjmp is still on the call stack. Afterwards its stack frame is gone.
  4. 4. Which resources are automatically released when longjmp skips over several function calls?

    longjmp just restores the saved registers and stack pointer. It runs no destructors or cleanup code, so skipped frames can leak memory, files and locks.
  5. 5. Why should a local variable modified between setjmp and longjmp be declared volatile?

    A non-volatile local changed after setjmp may live in a register that longjmp restores to an older value. volatile forces the compiler to keep the variable in memory.

Summary

  • setjmp(env) saves the context and returns 0; longjmp(env, v) restores it, making setjmp return v (or 1 if v is 0) a second time.
  • The jump unwinds any number of frames at once, which makes setjmp/longjmp a poor man's exception mechanism.
  • The function that called setjmp must still be active; jumping to a returned function or another thread is undefined behavior.
  • Locals changed between setjmp and longjmp should be volatile, or they are indeterminate after the jump.
  • No cleanup runs: malloced memory, files and locks held by skipped frames are your responsibility.
  • Use sigsetjmp/siglongjmp when jumping out of a signal handler, and prefer return codes or goto cleanup for everyday error handling.

Next: volatile and C11 Atomics