From 867079c820b3d9df472308244810782d0651cf08 Mon Sep 17 00:00:00 2001 From: Petri Lehtinen Date: Mon, 15 Apr 2013 08:42:23 +0300 Subject: [PATCH] json_dump*(): Don't crash if json is NULL and JSON_ENCODE_ANY is set --- src/dump.c | 3 +++ test/suites/api/test_dump.c | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/dump.c b/src/dump.c index bbf87d0..95840f2 100644 --- a/src/dump.c +++ b/src/dump.c @@ -171,6 +171,9 @@ static int object_key_compare_serials(const void *key1, const void *key2) static int do_dump(const json_t *json, size_t flags, int depth, json_dump_callback_t dump, void *data) { + if(!json) + return -1; + switch(json_typeof(json)) { case JSON_NULL: return dump("null", 4, data); diff --git a/test/suites/api/test_dump.c b/test/suites/api/test_dump.c index 8cd659c..334dbfa 100644 --- a/test/suites/api/test_dump.c +++ b/test/suites/api/test_dump.c @@ -9,6 +9,26 @@ #include #include "util.h" +static int encode_null_callback(void *ptr, size_t size, void *data) +{ + return 0; +} + +static void encode_null() +{ + if(json_dumps(NULL, JSON_ENCODE_ANY) != NULL) + fail("json_dumps didn't fail for NULL"); + + if(json_dumpf(NULL, stderr, JSON_ENCODE_ANY) != -1) + fail("json_dumpf didn't fail for NULL"); + + /* Don't test json_dump_file to avoid creating a file */ + + if(json_dump_callback(NULL, encode_null_callback, NULL, JSON_ENCODE_ANY) != -1) + fail("json_dump_callback didn't fail for NULL"); +} + + static void encode_twice() { /* Encode an empty object/array, add an item, encode again */ @@ -159,6 +179,7 @@ static void escape_slashes() static void run_tests() { + encode_null(); encode_twice(); circular_references(); encode_other_than_array_or_object();