diff options
| author | Xavier Del Campo Romero <xavi.dcr@tutanota.com> | 2023-03-04 02:06:19 +0100 |
|---|---|---|
| committer | Xavier Del Campo Romero <xavi.dcr@tutanota.com> | 2023-07-20 23:52:51 +0200 |
| commit | 67ffb772b7488b84e37e6880290820fc54434b33 (patch) | |
| tree | 574f95ad5834282261846daede1f653b1d1d0666 /html.c | |
| parent | 37fd5c92aebd87af14a1f73f8e567b8b74f6bd36 (diff) | |
Fix memory leak on failed realloc(3)
According to C99 ยง7.20.3.4:
If memory for the new object cannot be allocated, the old object is not
deallocated and its value is unchanged.
Therefore, a temporary pointer must be used to ensure the original
object can still be deallocated should realloc(3) return a null pointer.
Diffstat (limited to 'html.c')
| -rw-r--r-- | html.c | 13 |
1 files changed, 9 insertions, 4 deletions
@@ -101,25 +101,30 @@ int html_node_set_value_unescaped(struct html_node *const n, int html_node_add_attr(struct html_node *const n, const char *const attr, const char *const val) { - if (!(n->attrs = realloc(n->attrs, (n->n + 1) * sizeof *n->attrs))) + const size_t el = n->n + 1; + struct html_attribute *const attrs = realloc(n->attrs, + el * sizeof *n->attrs), *a = NULL; + + if (!attrs) { fprintf(stderr, "%s: realloc(3): %s\n", __func__, strerror(errno)); return -1; } - struct html_attribute *const a = &n->attrs[n->n++]; - + a = &attrs[n->n]; *a = (const struct html_attribute){0}; if (!(a->attr = strdup(attr)) || (val && !(a->value = strdup(val)))) { - fprintf(stderr, "%s: malloc(3): %s\n", __func__, strerror(errno)); + fprintf(stderr, "%s: strdup(3): %s\n", __func__, strerror(errno)); free(a->attr); free(a->value); return -1; } + n->attrs = attrs; + n->n = el; return 0; } |
