Portable equivalent to gcc's __attribute__(cleanup)
Asked Answered
C

6

17

Recently I came across a gcc extension that I have found rather useful: __attribute__(cleanup)

Basically, this allows you to assign a cleanup call to a local variable at the time it exits scope. For instance, given the following section of code, all memory must be maintained and handled explicitly in any and all cases within the call to foo.

void foo() {
   char * buff = ...; /* some memory allocation */
   char * buff2 = 0, * buff3 = 0;
   if (! buff) {
      return;
   } else {
      buff2 = ...; /* memory allocation */
      if (! buff2) {
         goto clean_exit;
      } else {
         /* ... and so on ... */
      }
   }

clean_exit:
   free (buff);
   free (buff2);
   free (buff3);
}

However, by using the extension that can reduce to

#define clean_pchar_scope __attribute__((cleanup(pchar_free)))

void pchar_free (char ** c) { free (*c); }

void foo () {
   char * buff clean_pchar_scope = ...; /* some memory allocation */
   char * buff2 clean_pchar_scope = 0, * buff3 clean_pchar_scope = 0;
   if (! buff)
      return;
   buff2 = ...; /* memory allocation */
   if (! buff2)
      return;
   /* and so on */
}

Now all memory is reclaimed on the basis of scope without the use of nested if/else or goto constructs coupled with a consolidated memory release section of the function. I realize that the use of goto could be avoided there for a more nested if/else construct (so, please, no holy wars on the goto...) and that the example is contrived, but the fact remains that this is can be quite a useful feature.

Unfortunately, as far as I know, this is gcc-specific. I'm interested in any portable ways to do the same thing (if they even exist). Has anyone had experiences in doing this with something other than gcc?

EDIT: Seems that portability is not in play. Considering that, is there a way to do this outside of the gcc space? It seems like to nice a feature to be gcc-specific...

Clomp answered 1/12, 2009 at 20:7 Comment(3)
somewhat related: #1602898Corycorybant
That is a little bit to coarse grained for what I'm looking for. In either case, it seems that that solution is still gcc specific (for the accepted answer) or C++ related for the class-based answer.Clomp
I believe the C committee is looking to add a standard defer statement that does what you want! Here (gustedt.wordpress.com/2020/12/14/a-defer-mechanism-for-c) is a blogpost that summarizes the paperZoba
J
11

There's no portable way in C.

Fortunately it's a standard feature of C++ with destructors.

Edit:

MSVC appears to have __try and __finally keywords which can be used for this purpose as well. This is different than the C++ exception handling and I think it's available in C.

I think you'll find that cleanup and try/finally aren't widely used specifically because of the implicit support in C++, which is "close enough" to C that people interested in the behavior can switch their code to C++ with ease.

Johnsten answered 1/12, 2009 at 20:13 Comment(1)
Ok, I've updated to ignore portability concerns. Outside of that, are you aware of ways to do this outside of gcc?Clomp
A
9

__attribute__(cleanup) is not gcc-specific, it is also supported by clang and icc, making msvc the only major compiler that doesn't support it (and that one is pretty useless for modern C development anyway).

So even if it is not in the ISO standard, it can be considered portable for most practical purposes.

Authoritative answered 12/3, 2019 at 22:2 Comment(0)
H
5

The first half of your question is the portable way to do it.

Hypabyssal answered 11/8, 2010 at 15:28 Comment(0)
P
3

We are going to exploit the fact that a for loop can do work at the end of each iteration and run the loop only for one iteration. The work we will do at the end is increment the counter and call a function to destruct the object. The x parameter is the variable you want to limit the lifetime of, and the fn parameter is the function or function-macro that will destruct the object. The CONCATENATE macro is just so that we do not get "shadow variable" warnings when we nest defer.

#define CONCATENATE_DETAIL(x, y) x##y
#define CONCATENATE(x, y) CONCATENATE_DETAIL(x, y)
#define defer(x, fn)                      \
  for (int CONCATENATE(i, __LINE__) = 0;  \
       CONCATENATE(i, __LINE__) == 0;     \
       CONCATENATE(i, __LINE__)++, fn((x)))

Rules and limitations:

  • The defer macro has the convenient feature that when nested, it destructs the objects in reverse order; this is what C++ does.
  • You have to declare the variable before using it in defer.
  • If you need to exit the defer block early you have to use continue. Using break or return will leak one or more objects.
  • If you get a warning that the x variable is used before it is initialized it is most likely because one of your code paths goes straight to the destruction function.
  • Most companies and open source projects will not let you use this macro. (This is probably an understatement.)
  • This list is not complete. Always test your code, especially code you find on the internet.

Here is an extended version of OP's code, using the defer macro. You should be able to drop this code straight into Godbolt.org and play around with it.

#include <stdio.h>
#include <stdlib.h>

#define CONCATENATE_DETAIL(x, y) x##y
#define CONCATENATE(x, y) CONCATENATE_DETAIL(x, y)
#define defer(x, fn)                      \
  for (int CONCATENATE(i, __LINE__) = 0;  \
       CONCATENATE(i, __LINE__) == 0;     \
       CONCATENATE(i, __LINE__)++, fn((x)))

void cleanup(char* p) { free(p); }

void foo(void) {
  char* buff1 = NULL;
  char* buff2 = NULL;
  char* buff3 = NULL;

  defer(buff1, cleanup) {
    buff1 = malloc(64);
    if (buff1 == NULL)
      continue;
    defer(buff2, free) {
      buff2 = malloc(64);
      if (buff2 == NULL)
        continue;
      defer(buff3, free) {
        buff3 = malloc(64);
        if (buff3 == NULL)
          continue;

        buff1[63] = '\0';
        buff2[63] = '\0';
        buff3[63] = '\0';

        puts(buff1);
        puts(buff2);
        puts(buff3);
      }
    }
  }
}

The defer code is my own but I saw something similar on Github years ago but, I can not find it now.

Pentaprism answered 12/12, 2019 at 17:54 Comment(0)
Z
2

@dpi says __attribute__(cleanup) is supported in GCC, clang, and ICC.

In this case, you can have a macro that expands to __attribute__(cleanup) in most compilers and falls back to a C++ implementation on MSVC. It would look something like this:

#if defined(__cplusplus)
  template<class F> struct finally{ 
    F f;
    ~finally() {f();}
  };

#  define WITH_CLEANUP(type, name, cleaner, ...)            \
   type name __VA_ARGS__;
   finally name # cleaner # __COUNTER__ = [&]{cleaner(&name);};
#elif
#  define WITH_CLEANUP(type, name, cleaner, ...)            \
      type name __attribute__(cleanup(cleaner)) __VA_ARGS__;
#endif
Zoba answered 12/3, 2021 at 14:43 Comment(0)
A
-3
void foo()
{
        char *buf1 = 0, *buf2 = 0, *buf3 = 0;
        /** more resource handle */

        do {

                if ( buf1 = ... , !buf1 ) break;
                if ( buf2 = ... , !buf2 ) break;
                if ( buf3 = ... , !buf3 ) break;

                /** to acquire more resource */

                /** to do with resource */

        } while (0);

        /** to release more resource */

        if (buf3) free(buf3);
        if (buf2) free(buf2);
        if (buf1) free(buf1);
}
Airfield answered 3/12, 2009 at 0:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.