From: Scott Bauer Date: Mon, 19 Sep 2016 15:47:15 +0000 (-0600) Subject: json: Print to stderr and abort() instead of returning NULL and faulting. X-Git-Tag: v1.0~60^2 X-Git-Url: https://www.infradead.org/git/?a=commitdiff_plain;h=8e7e12a42c075f7dc2511fe56cce1f3ba548a5bb;p=users%2Fsagi%2Fnvme-cli.git json: Print to stderr and abort() instead of returning NULL and faulting. No one who uses the JSON API is checking for return values. Instead of littering the json code with if-else chains, we will error on any memory allocation failure. Even though incredibly unlikely malloc will return NULL it's easier to check for it and print an error instead of faulting. Signed-off-by: Scott Bauer --- diff --git a/json.c b/json.c index 65fdd6fe..e9fcf077 100644 --- a/json.c +++ b/json.c @@ -5,14 +5,26 @@ #include #include "json.h" +static inline void fail_and_notify(void) +{ + fprintf(stderr, "Allocation of memory for json object failed, aborting.\n"); + __builtin_abort(); +} + struct json_object *json_create_object(void) { - return calloc(1, sizeof(struct json_object)); + void *test = calloc(1, sizeof(struct json_object)); + if (!test) + fail_and_notify(); + return test; } struct json_array *json_create_array(void) { - return calloc(1, sizeof(struct json_array)); + void *test = calloc(1, sizeof(struct json_array)); + if (!test) + fail_and_notify(); + return test; } static struct json_pair *json_create_pair(const char *name, struct json_value *value) @@ -24,7 +36,9 @@ static struct json_pair *json_create_pair(const char *name, struct json_value *v value->parent_type = JSON_PARENT_TYPE_PAIR; value->parent_pair = pair; - } + } else + fail_and_notify(); + return pair; } @@ -35,7 +49,9 @@ static struct json_value *json_create_value_int(long long number) if (value) { value->type = JSON_TYPE_INTEGER; value->integer_number = number; - } + } else + fail_and_notify(); + return value; } @@ -46,7 +62,9 @@ static struct json_value *json_create_value_float(long double number) if (value) { value->type = JSON_TYPE_FLOAT; value->float_number = number; - } + } else + fail_and_notify(); + return value; } @@ -66,6 +84,9 @@ static char *strdup_escape(const char *str) } p = ret = malloc(strlen(str) + escapes + 1); + if (!ret) + fail_and_notify(); + while (*str) { if (*str == '\\' || *str == '\"') *p++ = '\\'; @@ -91,6 +112,9 @@ static struct json_value *json_create_value_string(const char *str) value = NULL; } } + if (!value) + fail_and_notify(); + return value; } @@ -102,7 +126,9 @@ static struct json_value *json_create_value_object(struct json_object *obj) value->type = JSON_TYPE_OBJECT; value->object = obj; obj->parent = value; - } + } else + fail_and_notify(); + return value; } @@ -114,7 +140,9 @@ static struct json_value *json_create_value_array(struct json_array *array) value->type = JSON_TYPE_ARRAY; value->array = array; array->parent = value; - } + } else + fail_and_notify(); + return value; }