]> git.kaiwu.me - klib.git/commitdiff
Add ks_release() to kstring.h
authorJohn Marshall <jm18@sanger.ac.uk>
Wed, 12 Mar 2014 14:33:12 +0000 (14:33 +0000)
committerJohn Marshall <jm18@sanger.ac.uk>
Thu, 2 Jul 2015 09:23:15 +0000 (10:23 +0100)
Using this function is a more explicit way of transferring ownership
than just "foo = str.s"; the latter leaves room for readers to wonder
whether a subsequent "free(str.s)" has been forgotten.

kstring.h

index 0e654cb82dac9ce9a8642dbb3fede4ba7e199ea2..2567efcb721f273f82f435b291abea7c7565dd1c 100644 (file)
--- a/kstring.h
+++ b/kstring.h
@@ -49,9 +49,8 @@
  *       kstring_t str = { 0, 0, NULL };
  *       kstring_t str; ...; str.l = str.m = 0; str.s = NULL;
  * and either ownership of the underlying buffer should be given away before
- * the object disappears (i.e., the str.s pointer copied and something else
- * responsible for freeing it), or the kstring_t should be destroyed with
- *       free(str.s);  */
+ * the object disappears (see ks_release() below) or the kstring_t should be
+ * destroyed with  free(str.s);  */
 #ifndef KSTRING_T
 #define KSTRING_T kstring_t
 typedef struct __kstring_t {
@@ -111,6 +110,18 @@ static inline size_t ks_len(kstring_t *s)
        return s->l;
 }
 
+// Give ownership of the underlying buffer away to something else (making
+// that something else responsible for freeing it), leaving the kstring_t
+// empty and ready to be used again, or ready to go out of scope without
+// needing  free(str.s)  to prevent a memory leak.
+static inline char *ks_release(kstring_t *s)
+{
+       char *ss = s->s;
+       s->l = s->m = 0;
+       s->s = NULL;
+       return ss;
+}
+
 static inline int kputsn(const char *p, int l, kstring_t *s)
 {
        if (s->l + l + 1 >= s->m) {