summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSerge Zaitsev <zaitsev.serge@gmail.com>2015-10-25 22:42:48 +0200
committerSerge Zaitsev <zaitsev.serge@gmail.com>2015-10-25 22:42:48 +0200
commit2db03781c59bd59cbb9269d6e5793b884c788816 (patch)
treec5b21c08bce15b46fa0a7e49cf5253344033d436
parent0c2d60b8e7820857fe14dfd113a90c94b2f18611 (diff)
parent2d185aa465782ba30bfaea5ccd39cea4917e69a8 (diff)
Merge pull request #55 from goriy/example_realloc_fix
small fix of jsondump example for cases of realloc failures
-rw-r--r--example/jsondump.c21
1 files changed, 17 insertions, 4 deletions
diff --git a/example/jsondump.c b/example/jsondump.c
index 3490bbf49..7be628772 100644
--- a/example/jsondump.c
+++ b/example/jsondump.c
@@ -4,6 +4,21 @@
#include <errno.h>
#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;