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-03-04 03:03:15 +0100 |
| commit | 62bdf9f72f6a65b76bbb97ffa467e16217646cbc (patch) | |
| tree | e290a93f97ecbedcea1f7731de488f12ce5b5a42 /html.c | |
| parent | d83e8ad1baaff1d445c96a269da89a833dfa5d91 (diff) | |
| download | slcl-62bdf9f72f6a65b76bbb97ffa467e16217646cbc.tar.gz | |
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; } |
