Course contentsShow
← C
Lesson 960 of 1,21913. Advanced CFree lesson

The 'Clobber' list explained

The 'Clobber' list explained

What you'll learn: How to tell the C compiler which CPU registers are being modified by your assembly code to prevent data corruption.

The "Borrowing the Desk" Analogy

Imagine you are a guest worker in an office. The C compiler is the permanent employee who uses the office desk (the CPU registers) to keep track of their ongoing work. When you write inline assembly, you are stepping into that office to perform a specific task.

If you walk in, grab a random folder on the desk, scribble over the notes, and leave, the permanent employee will return to a mess. They assume the data they left in those "folders" is still intact. To prevent a crash, you must leave a note on the desk saying: "I touched folders A and B. Do not trust what is currently in them."

In C, that "note" is the clobber list.

Why the compiler needs a heads-up

The C compiler is an expert at optimization. It often keeps important variables inside CPU registers (like eax or rbx) because accessing registers is faster than accessing RAM.

When you inject assembly using asm(), the compiler doesn't actually read your assembly string to see what you're doing. It treats it like a "black box." If your assembly code changes the value of a register that the compiler was using to store a local variable, your program will behave unpredictably or crash.

The Clobber Syntax

The clobber list is the third colon-separated section of an asm block: asm(code : outputs : inputs : clobbers);

void clobber_example() {
    long result;
    long input_val = 10;

    // We use the 'rdx' register manually in our assembly code.
    // We MUST list "rdx" in the clobber list so the compiler
    // moves its own data out of rdx before our code runs.
    __asm__ (
        "movq %1, %%rdx;"
        "addq $5, %%rdx;"
        "movq %%rdx, %0;"
        : "=r" (result)      // Output
        : "r" (input_val)    // Input
        : "rdx", "cc"        // Clobber list: we changed rdx and condition codes (flags)
    );
}

In the example above, listing "rdx" tells the compiler: "I am going to overwrite the RDX register. If you have anything important there, save it somewhere else first." The "cc" entry is another common clobber, telling the compiler that your assembly might have changed the CPU's status flags (like the Zero or Carry flags).

Key takeaway

The clobber list is a safety contract that protects the compiler’s data from being accidentally overwritten by your manual assembly instructions.