[PATCH 12/35] monitor: add helpers for __attribute__((cleanup))

mwilck at suse.com mwilck at suse.com
Tue Jan 26 15:33:01 EST 2021


From: Martin Wilck <mwilck at suse.com>

__attribute__((cleanup)) is very helpful but ugly. Try to avoid
defining lots of cleanup functions with these macros.

Usage: to declare an auto-cleanup variable of type (some_type *),
write

CLEANUP_FUNC(some_type)

void some_func(void)
{
        CLEANUP(some_type, varname) = NULL;
	...
}

Signed-off-by: Martin Wilck <mwilck at suse.com>
---
 common.h | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/common.h b/common.h
index 1c214a4..9386ec5 100644
--- a/common.h
+++ b/common.h
@@ -12,4 +12,16 @@
 #define __stringify_1(x...) #x
 #define __stringify(x...)  __stringify_1(x)
 
+#define CLEANUP_FUNC(type) \
+static void __cleanup_ ## type ##_p(type ** __p) \
+{						 \
+	if (*__p) {				 \
+		free(*__p);			 \
+		*__p = NULL;			 \
+	}					 \
+}
+
+#define CLEANUP(__t, __v) \
+	__t *__v __attribute__((cleanup(__cleanup_ ## __t ## _p)))
+
 #endif
-- 
2.29.2




More information about the Linux-nvme mailing list