util: add helpers for automatic cleanup of strings on scope exit
Leverage the cleanup attribute to attach automatic cleanup calls to
C strings. Annoyingly we can't seem to generalize this, so we need
a unique define & name for each pointer type.
Bug: None
Test: unittests pass
Change-Id: I99db232382156f4e844c230bcfb90be8dcd59ce8
diff --git a/util.h b/util.h
index d341cda..230bb62 100644
--- a/util.h
+++ b/util.h
@@ -104,6 +104,21 @@
close(*fd);
}
+/*
+ * Automatically free a heap allocation when exiting its scope.
+ * Make sure the pointer is always initialized.
+ * Some examples:
+ * attribute_cleanup_str char *s = strdup(...);
+ * attribute_cleanup_str char *s = NULL;
+ * ...
+ * s = strdup(...);
+ */
+#define attribute_cleanup_str attribute_cleanup(_cleanup_str)
+static inline void _cleanup_str(char **ptr)
+{
+ free(*ptr);
+}
+
#endif /* __cplusplus */
/* clang-format off */