Tech News
← Back to articles

Defer: Resource cleanup in C with GCCs magic

read original related products more articles

Defer Macro

Warning: This is experimental, relies on GCC-specific extensions (__attribute__((cleanup)) and nested functions), and is not portable C. It’s just for fun and exploration.

While working on my operating system project, RetrOS-32, I ran into some of GCC’s less common

Here’s an example: While working on my operating system project, RetrOS-32, I ran into some of GCC’s less common function attributes . One that stood out to me was the cleanup attribute, which lets you tie a function to a variable. When the variable goes out of scope, that function is called automatically. At first this sounded like an easy way to manage resources in C, a language where you normally have to handle everything by hand.Here’s an example:

/* The function must take one parameter, * a pointer to a type compatible with the variable. * The return value of the function (if any) is ignored. */ void free_ptr(void* ptr) { free(*(void**)ptr); } int example(){ __attribute(cleanup(free_ptr)) char* ptr = malloc(32); return 0; }

... continue reading