From e709651a20f3b32c5cca9e3ca29c6b0b43bbb4d8 Mon Sep 17 00:00:00 2001 From: goriy Date: Sat, 24 Oct 2015 23:32:51 +0300 Subject: [PATCH] small fix of jsondump example for cases of realloc failures When realloc() function fails it returns NULL pointer. But old data pointer remains valid in such a case. It's a mistake to use old data pointer to store new pointer returned by realloc. In case of realloc failure, pointer is overwritten with NULL value, but old used memory remains unreferenced and could not be even freed anymore. Such mistakes could lead to memory leaks. --- example/jsondump.c | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/example/jsondump.c b/example/jsondump.c index 3490bbf..a5b5972 100644 --- a/example/jsondump.c +++ b/example/jsondump.c @@ -48,7 +48,7 @@ static int dump(const char *js, jsmntok_t *t, size_t count, int indent) { int main() { int r; int eof_expected = 0; - char *js = NULL; + char *tmp, *js = NULL; size_t jslen = 0; char buf[BUFSIZ]; @@ -82,11 +82,13 @@ int main() { } } - js = realloc(js, jslen + r + 1); - if (js == NULL) { + tmp = realloc(js, jslen + r + 1); + if (tmp == NULL) { + free (js); fprintf(stderr, "realloc(): errno=%d\n", errno); return 3; } + js = tmp; strncpy(js + jslen, buf, r); jslen = jslen + r; @@ -94,12 +96,16 @@ again: r = jsmn_parse(&p, js, jslen, tok, tokcount); if (r < 0) { if (r == JSMN_ERROR_NOMEM) { + jsmntok_t *tmptok; + tokcount = tokcount * 2; - tok = realloc(tok, sizeof(*tok) * tokcount); - if (tok == NULL) { + tmptok = realloc(tok, sizeof(*tok) * tokcount); + if (tmptok == NULL) { + free (tok); fprintf(stderr, "realloc(): errno=%d\n", errno); return 3; } + tok = tmptok; goto again; } } else {