Search code examples
craii

Implementing RAII in pure C?


Is it possible to implement RAII in pure C?

I assume it isn't possible in any sane way, but perhaps is it possible using some kind of dirty trick. Overloading the standard free function comes to mind or perhaps overwriting the return address on the stack so that when the function returns, it calls some other function that somehow releases resources? Or maybe with some setjmp/longjmp trick?

This is of a purely academic interest and I have no intention of actually writing such unportable and crazy code but I'm wondering if that is at all possible.


Solution

  • This is inherent implementation dependent, since the Standard doesn't include such a possibility. For GCC, the cleanup attribute runs a function when a variable goes out of scope:

    #include <stdio.h>
    
    void scoped(int * pvariable) {
        printf("variable (%d) goes out of scope\n", *pvariable);
    }
    
    int main(void) {
        printf("before scope\n");
        {
            int watched __attribute__((cleanup (scoped)));
            watched = 42;
        }
        printf("after scope\n");
    }
    

    Prints:

    before scope
    variable (42) goes out of scope
    after scope
    

    See here