[Libguestfs] [PATCH nbdkit RFC 1/2] common: Add <vector>_reset which removes all elements of a vector.

Richard W.M. Jones rjones at redhat.com
Tue Jul 14 16:56:29 UTC 2020


It sets the size back to 0 and deallocates the underlying vector.

Note that if the vector elements are allocated (eg. strings) this does
not free them, so the correct way to fully deallocate a vector of
non-const strings might be:

  string_vector_iter (&strings, (void *) free);
  string_vector_reset (&strings);
---
 common/utils/vector.h | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/common/utils/vector.h b/common/utils/vector.h
index 15733e54..6468fd9b 100644
--- a/common/utils/vector.h
+++ b/common/utils/vector.h
@@ -126,6 +126,15 @@
     v->size--;                                                          \
   }                                                                     \
                                                                         \
+  /* Remove all elements and deallocate the vector. */                  \
+  static inline void                                                    \
+  name##_reset (name *v)                                                \
+  {                                                                     \
+    free (v->ptr);                                                      \
+    v->ptr = NULL;                                                      \
+    v->size = v->alloc = 0;                                             \
+  }                                                                     \
+                                                                        \
   /* Iterate over the vector, calling f() on each element. */           \
   static inline void                                                    \
   name##_iter (name *v, void (*f) (type elem))                          \
-- 
2.27.0




More information about the Libguestfs mailing list