0

I am using the json-c in my C program (not C++). I am getting segfaults from time to time and trying to debug. To be honest, I might not have the full understanding how the library works so I am looking for any advice.

This is partially how I am using:

char* createjsonstatusstring()
{
json_object     *jsonmain,
                *jsontmp;
const char      *conststring;
char            *string;

jsonmain = json_object_new_object();
jsontmp = json_object_new_object();
json_object_object_add(jsontmp,"test",json_object_new_string("Beispiel"));
json_object_object_add(jsontmp,"test2",json_object_new_string("Beispiel2"));
json_object_object_add(jsonmain,"Data",jsontmp);

conststring = json_object_to_json_string_ext(jsonmain,JSON_C_TO_STRING_SPACED | JSON_C_TO_STRING_PRETTY); 
json_object_put(jsontmp);
json_object_put(jsonmain);

string = malloc(strlen(conststring)+1);
strcpy(string,conststring);
return string;
}

When doing the last json_object_put I am getting the segfault. Can you explain why and how to improve?

Thanks!

/KNEBB

Christian
  • 169
  • 8
  • Why are you using `json_object_new_array`? Arrays are indexed with numbers, not with string keys. You use `json_object_array_add` with `json_object_new_array` and `json_object_object_add` with `json_object_new_object`. – n. m. could be an AI Jan 21 '23 at 10:45
  • You are right. Fixed it. Indeed I am using _new_object... – Christian Jan 21 '23 at 11:57
  • `string = malloc(strlen(conststring)+1); strcpy(string,conststring);`? Just use `strdup()`. Some heads may explode, but `strdup()` **will** be [standard in C23](https://www.iso-9899.info/n3047.html#7.26.2.6) Of course, come 2050 or so, Microsoft will be bragging about how they're *working* to *become* somewhat *less* C23 non-compliant... – Andrew Henle Jan 21 '23 at 12:21

1 Answers1

1

From https://json-c.github.io/json-c/json-c-0.10/doc/html/json__object_8h.html#a04448b1c63173e1bfe49965835732075 :

void json_object_object_add     (   struct json_object *    obj,
        const char *    key,
        struct json_object *    val  
    )   

Upon calling this, the ownership of val transfers to obj. [..]

and

void json_object_put    (   struct json_object *    obj      )      

Decrement the reference count of json_object and free if it reaches zero. You must have ownership of obj prior to doing this or you will cause an imbalance in the reference count.

You do not have ownership in jsontmp, so doing json_object_put(jsontmp); is invalid. Just only call json_object_put(jsonmain);, jsonmain has ownership of jsontmp.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111