From 1f019ceea1ed39286e6bccfb3ff936c22fe0f7c0 Mon Sep 17 00:00:00 2001 From: Matthias Schiffer Date: Tue, 21 Jun 2016 17:19:10 +0200 Subject: Fix various memory management issues Consistently handle allocation failures. Some functions are changed to return bool or int instead of void to allow returning an error. Also fix a buffer size miscalculation in lua/uloop and use _exit() instead of exit() on errors after forking. Signed-off-by: Matthias Schiffer --- blobmsg_json.c | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) (limited to 'blobmsg_json.c') diff --git a/blobmsg_json.c b/blobmsg_json.c index 5713948..2e318b2 100644 --- a/blobmsg_json.c +++ b/blobmsg_json.c @@ -119,15 +119,22 @@ struct strbuf { static bool blobmsg_puts(struct strbuf *s, const char *c, int len) { + size_t new_len; + char *new_buf; + if (len <= 0) return true; if (s->pos + len >= s->len) { - s->len += 16 + len; - s->buf = realloc(s->buf, s->len); - if (!s->buf) + new_len = s->len + 16 + len; + new_buf = realloc(s->buf, new_len); + if (!new_buf) return false; + + s->len = new_len; + s->buf = new_buf; } + memcpy(s->buf + s->pos, c, len); s->pos += len; return true; @@ -290,14 +297,18 @@ char *blobmsg_format_json_with_cb(struct blob_attr *attr, bool list, blobmsg_jso { struct strbuf s; bool array; + char *ret; s.len = blob_len(attr); - s.buf = malloc(s.len); s.pos = 0; s.custom_format = cb; s.priv = priv; s.indent = false; + s.buf = malloc(s.len); + if (!s.buf) + return NULL; + if (indent >= 0) { s.indent = true; s.indent_level = indent; @@ -316,8 +327,13 @@ char *blobmsg_format_json_with_cb(struct blob_attr *attr, bool list, blobmsg_jso return NULL; } - s.buf = realloc(s.buf, s.pos + 1); - s.buf[s.pos] = 0; + ret = realloc(s.buf, s.pos + 1); + if (!ret) { + free(s.buf); + return NULL; + } + + ret[s.pos] = 0; - return s.buf; + return ret; } -- cgit v1.2.3