12

C can do C++ - Like Destructors too!

Use this:

static inline void cln_fptr(FILE **f) {
    fclose(*f);
}
static void foo(void) {
     __attribute__((cleanup(cln_fptr))) FILE *f;
    f = fopen("/etc/passwd", "r");
    // [...]
}
#SecureCoding #C/C++

The RAII pattern in C++ is very convenient and helps avoiding certain types of bugs. Resource management is tied to the scope of stack objects and effectively handed over to compiler generated code. Forgetting to free a buffer or unlock a mutex is no longer an issue.

In C programs, a similar pattern can be achieved through a gcc extension. A stack variable can specify a function to be called when it goes out of scope using the __cleanup__ attribute. This approach is extensively used in large code bases like systemd for RAII-style resource management.

Icon with a waving hand

Get in touch

sigma star gmbh
Eduard-Bodem-Gasse 6, 1st floor
6020 Innsbruck | Austria

sigma star gmbh logo