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.
master
goriy 9 years ago
parent 0c2d60b8e7
commit e709651a20

@ -48,7 +48,7 @@ static int dump(const char *js, jsmntok_t *t, size_t count, int indent) {
int main() { int main() {
int r; int r;
int eof_expected = 0; int eof_expected = 0;
char *js = NULL; char *tmp, *js = NULL;
size_t jslen = 0; size_t jslen = 0;
char buf[BUFSIZ]; char buf[BUFSIZ];
@ -82,11 +82,13 @@ int main() {
} }
} }
js = realloc(js, jslen + r + 1); tmp = realloc(js, jslen + r + 1);
if (js == NULL) { if (tmp == NULL) {
free (js);
fprintf(stderr, "realloc(): errno=%d\n", errno); fprintf(stderr, "realloc(): errno=%d\n", errno);
return 3; return 3;
} }
js = tmp;
strncpy(js + jslen, buf, r); strncpy(js + jslen, buf, r);
jslen = jslen + r; jslen = jslen + r;
@ -94,12 +96,16 @@ again:
r = jsmn_parse(&p, js, jslen, tok, tokcount); r = jsmn_parse(&p, js, jslen, tok, tokcount);
if (r < 0) { if (r < 0) {
if (r == JSMN_ERROR_NOMEM) { if (r == JSMN_ERROR_NOMEM) {
jsmntok_t *tmptok;
tokcount = tokcount * 2; tokcount = tokcount * 2;
tok = realloc(tok, sizeof(*tok) * tokcount); tmptok = realloc(tok, sizeof(*tok) * tokcount);
if (tok == NULL) { if (tmptok == NULL) {
free (tok);
fprintf(stderr, "realloc(): errno=%d\n", errno); fprintf(stderr, "realloc(): errno=%d\n", errno);
return 3; return 3;
} }
tok = tmptok;
goto again; goto again;
} }
} else { } else {

Loading…
Cancel
Save