diff mbox

[OpenWrt-Devel,v2,07/10] jshn: add error handling and fix memory leak in jshn_format().

Message ID 1415800763-14311-8-git-send-email-yszhou4tech@gmail.com
State Accepted
Headers show

Commit Message

Yousong Zhou Nov. 12, 2014, 1:59 p.m. UTC
Though currently jshn is more a one-shot data transformation tool and
won't leak much memory in its lifetime, people may use it as example
code, so do it right.

Signed-off-by: Yousong Zhou <yszhou4tech@gmail.com>
---
 jshn.c |   23 ++++++++++++++++++-----
 1 file changed, 18 insertions(+), 5 deletions(-)
diff mbox

Patch

diff --git a/jshn.c b/jshn.c
index 431e1b3..69cb06f 100644
--- a/jshn.c
+++ b/jshn.c
@@ -258,18 +258,31 @@  static int jshn_format(bool no_newline, bool indent)
 {
 	json_object *obj;
 	const char *output;
+	char *blobmsg_output = NULL;
+	int ret = -1;
+
+	if (!(obj = json_object_new_object()))
+		return -1;
 
-	obj = json_object_new_object();
 	jshn_add_objects(obj, "J_V", false);
-	output = json_object_to_json_string(obj);
+	if (!(output = json_object_to_json_string(obj)))
+		goto out;
+
 	if (indent) {
 		blob_buf_init(&b, 0);
-		blobmsg_add_json_from_string(&b, output);
-		output = blobmsg_format_json_indent(b.head, 1, 0);
+		if (!blobmsg_add_json_from_string(&b, output))
+			goto out;
+		if (!(blobmsg_output = blobmsg_format_json_indent(b.head, 1, 0)))
+			goto out;
+		output = blobmsg_output;
 	}
 	fprintf(stdout, "%s%s", output, no_newline ? "" : "\n");
+	free(blobmsg_output);
+	ret = 0;
+
+out:
 	json_object_put(obj);
-	return 0;
+	return ret;
 }
 
 static int usage(const char *progname)