[Libguestfs] [PATCH nbdkit 7/9] common/utils: Add CLEANUP_FREE_STRING_LIST macro.

Richard W.M. Jones
Wed, 15 Apr 2020 16:16:48 -0000

This automatically frees an argv-style list of strings, such as a copy
of environ.
---
 common/utils/cleanup.h |  3 +++
 common/utils/cleanup.c | 13 +++++++++++++
 2 files changed, 16 insertions(+)

diff --git a/common/utils/cleanup.h b/common/utils/cleanup.h
index 7070290d..14ffc7ff 100644
--- a/common/utils/cleanup.h
+++ b/common/utils/cleanup.h
@@ -40,6 +40,9 @@
 extern void cleanup_free (void *ptr);
 #define CLEANUP_FREE __attribute__((cleanup (cleanup_free)))

+extern void cleanup_free_string_list (char ***ptr);
+#define CLEANUP_FREE_STRING_LIST __attribute__((cleanup
(cleanup_free_string_list)))
+
 extern void cleanup_unlock (pthread_mutex_t **ptr);
 #define CLEANUP_UNLOCK __attribute__((cleanup (cleanup_unlock)))

diff --git a/common/utils/cleanup.c b/common/utils/cleanup.c
index fb77805b..a9759ec4 100644
--- a/common/utils/cleanup.c
+++ b/common/utils/cleanup.c
@@ -44,6 +44,19 @@ cleanup_free (void *ptr)
   free (* (void **) ptr);
 }

+void
+cleanup_free_string_list (char ***ptr)
+{
+  size_t i;
+  char **argv = *ptr;
+
+  if (argv == NULL) return;
+
+  for (i = 0; argv[i] != NULL; ++i)
+    free (argv[i]);
+  free (argv);
+}
+
 void
 cleanup_unlock (pthread_mutex_t **ptr)
 {
--
2.25.0