Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Improved containers handling of autofree items

* zhash duplicates item value if container has autofree set
* zlist duplicates item if container has autofree set

This is to get around anti-pattern where caller is responsible for strdup,
and forgetting it causes a double-free. It's easier to detect a dangling
allocation than a double-free.
  • Loading branch information...
commit 8f2904ff8ade1795d51a0d7303815a1c94c493fa 1 parent 8f8528a
@hintjens hintjens authored
Showing with 19 additions and 3 deletions.
  1. +11 −3 src/zhash.c
  2. +8 −0 src/zlist.c
View
14 src/zhash.c
@@ -246,6 +246,10 @@ zhash_insert (zhash_t *self, const char *key, void *value)
self->items = new_items;
self->limit = new_limit;
}
+ // If necessary, take duplicate of item (string) value
+ if (self->autofree)
+ value = strdup ((char *) value);
+
return s_item_insert (self, key, value)? 0: -1;
}
@@ -268,6 +272,10 @@ zhash_update (zhash_t *self, const char *key, void *value)
else
if (self->autofree)
free (item->value);
+
+ // If necessary, take duplicate of item (string) value
+ if (self->autofree)
+ value = strdup ((char *) value);
item->value = value;
}
else
@@ -389,7 +397,7 @@ zhash_dup (zhash_t *self)
for (index = 0; index != self->limit; index++) {
item_t *item = self->items [index];
while (item) {
- zhash_insert (copy, item->key, strdup (item->value));
+ zhash_insert (copy, item->key, item->value);
item = item->next;
}
}
@@ -412,7 +420,7 @@ zhash_keys (zhash_t *self)
for (index = 0; index != self->limit; index++) {
item_t *item = self->items [index];
while (item) {
- zlist_append (keys, strdup (item->key));
+ zlist_append (keys, item->key);
item = item->next;
}
}
@@ -498,7 +506,7 @@ zhash_load (zhash_t *self, char *filename)
if (!equals)
break; // Some error, stop parsing it
*equals++ = 0;
- zhash_update (self, buffer, strdup (equals));
+ zhash_update (self, buffer, equals);
}
fclose (handle);
return 0;
View
8 src/zlist.c
@@ -177,6 +177,10 @@ zlist_append (zlist_t *self, void *item)
if (!node)
return -1;
+ // If necessary, take duplicate of (string) item
+ if (self->autofree)
+ item = strdup ((char *) item);
+
node->item = item;
if (self->tail)
self->tail->next = node;
@@ -202,6 +206,10 @@ zlist_push (zlist_t *self, void *item)
if (!node)
return -1;
+ // If necessary, take duplicate of (string) item
+ if (self->autofree)
+ item = strdup ((char *) item);
+
node->item = item;
node->next = self->head;
self->head = node;
Please sign in to comment.
Something went wrong with that request. Please try again.