]> git.ipfire.org Git - thirdparty/libvirt.git/commitdiff
util: alloc: Add automatic cleanup/disposal of strings
authorPeter Krempa <pkrempa@redhat.com>
Mon, 1 Apr 2019 13:04:53 +0000 (15:04 +0200)
committerPeter Krempa <pkrempa@redhat.com>
Wed, 3 Apr 2019 09:58:10 +0000 (11:58 +0200)
VIR_AUTODISPOSE_STR is similar to VIR_AUTOFREE(char *) but uses
virDispose for clearing of the stored string.

This patch also refactors VIR_DISPOSE to use the new helper which is
used for the new macro.

Signed-off-by: Peter Krempa <pkrempa@redhat.com>
Reviewed-by: Ján Tomko <jtomko@redhat.com>
src/libvirt_private.syms
src/util/viralloc.c
src/util/viralloc.h

index 56143f6204fe9b2cc93c2c4f1e6eb0ce8a8283dc..46e5ad34e32df8da1d885eb0d288eefc599a1d2b 100644 (file)
@@ -1428,6 +1428,7 @@ virAllocTestOOM;
 virAllocVar;
 virDeleteElementsN;
 virDispose;
+virDisposeString;
 virExpandN;
 virFree;
 virInsertElementsN;
index b58329476038b27480c923f6a433e12303b219eb..e82bfa0acd96a10a9c745d40b54bb7fee339f158 100644 (file)
@@ -618,3 +618,19 @@ void virDispose(void *ptrptr,
         *countptr = 0;
     errno = save_errno;
 }
+
+
+/**
+ * virDisposeString:
+ * @ptrptr: pointer to pointer for a string which should be sanitized and cleared
+ *
+ * See virDispose.
+ */
+void
+virDisposeString(char **strptr)
+{
+    if (!*strptr)
+        return;
+
+    virDispose(strptr, strlen(*strptr), sizeof(char), NULL);
+}
index 226d4d9b648367bf63ad227fd7832c1ca6323d5a..a1708b772ce0bbab4dbf29bee1e75641cb8ac595 100644 (file)
@@ -79,6 +79,8 @@ void virFree(void *ptrptr) ATTRIBUTE_NONNULL(1);
 
 void virDispose(void *ptrptr, size_t count, size_t element_size, size_t *countptr)
     ATTRIBUTE_NONNULL(1);
+void virDisposeString(char **strptr)
+    ATTRIBUTE_NONNULL(1);
 
 /**
  * VIR_ALLOC:
@@ -575,9 +577,17 @@ void virDispose(void *ptrptr, size_t count, size_t element_size, size_t *countpt
  *
  * This macro is not safe to be used on arguments with side effects.
  */
-# define VIR_DISPOSE_STRING(ptr) virDispose(1 ? (void *) &(ptr) : (ptr), \
-                                            (ptr) ? strlen((ptr)) : 0, 1, NULL)
+# define VIR_DISPOSE_STRING(ptr) virDisposeString(&(ptr))
 
+/**
+ * VIR_AUTODISPOSE_STR:
+ *
+ * Macro to automatically free and clear the memory allocated to
+ * the string variable declared with it by calling virDisposeString
+ * when the variable goes out of scope.
+ */
+# define VIR_AUTODISPOSE_STR \
+    __attribute__((cleanup(virDisposeString))) char *
 
 /**
  * VIR_DISPOSE: