RAII is just automation and semantic sugar for something like this (or the equivalent set of goto labels that do the freeing at the end of the function):
{
void *buffer = malloc(SIZE_MAX);
if (buffer) {
if (!do_stuff(buffer)) {
free(buffer);
return;
}
more_stuff(buffer);
free(buffer);
}
return;
}
If you wanted something like that in C it doesn't need to emulate C++ style RAII with classes and strongly typed constructors. It could look like something like, for example, where you just define pairs of allocator and free functions: allocdef void *autobuffer(malloc, free);
...
{
autobuffer buffer(SIZE_MAX);
if (buffer) {
if (do_stuff(buffer)) {
return;
}
more_stuff(buffer);
}
return;
}
The implementation would effectively be a Lisp style macro expansion encoded in the C compiler (or preprocessor) that would just basically write out the equivalent of the first listing above.