diff --git a/example/jsondump.c b/example/jsondump.c index 3490bbf..7be6287 100644 --- a/example/jsondump.c +++ b/example/jsondump.c @@ -4,6 +4,21 @@ #include #include "../jsmn.h" +/* Function realloc_it() is a wrapper function for standart realloc() + * with one difference - it frees old memory pointer in case of realloc + * failure. Thus, DO NOT use old data pointer in anyway after call to + * realloc_it(). If your code has some kind of fallback algorithm if + * memory can't be re-allocated - use standart realloc() instead. + */ +static inline void *realloc_it(void *ptrmem, size_t size) { + void *p = realloc(ptrmem, size); + if (!p) { + free (ptrmem); + fprintf(stderr, "realloc(): errno=%d\n", errno); + } + return p; +} + /* * An example of reading JSON from stdin and printing its content to stdout. * The output looks like YAML, but I'm not sure if it's really compatible. @@ -82,9 +97,8 @@ int main() { } } - js = realloc(js, jslen + r + 1); + js = realloc_it(js, jslen + r + 1); if (js == NULL) { - fprintf(stderr, "realloc(): errno=%d\n", errno); return 3; } strncpy(js + jslen, buf, r); @@ -95,9 +109,8 @@ again: if (r < 0) { if (r == JSMN_ERROR_NOMEM) { tokcount = tokcount * 2; - tok = realloc(tok, sizeof(*tok) * tokcount); + tok = realloc_it(tok, sizeof(*tok) * tokcount); if (tok == NULL) { - fprintf(stderr, "realloc(): errno=%d\n", errno); return 3; } goto again;