Search code examples
cjsonstringcjson

Why my program crashes after second usage of a string in different functions?


When I run my program , it calls a function that have a "char *msgtype" and this function work probably but when another function use a different "char *msgtype" in it when program reach the line that contain it , program crashes(and even when the firs function is called for second time program crashes). What is the problem ?

and if I change the name in the second function it just work one time and after calling that function again program crashes !

void fun1(){
    ...

    cJSON *root = cJSON_Parse(buffer);
    char *msgtype = cJSON_GetObjectItem(root,"type")->valuestring;

    ...

    free(msgtype);
    cJSON_Delete(root);

    ...
}

void fun2(){
    ...

    cJSON *root = cJSON_Parse(buffer);
    char *msgtype = cJSON_GetObjectItem(root,"type")->valuestring;//it crashes here

    ...

    free(msgtype);
    cJSON_Delete(root);

    ...
}

int main(){
    fun1();
    fun2();//it crashes inside this function !
}

Solution

  • Do you know what cJSON_GetObjectItem() returns? Is it a pointer into a data structure, or a copy of the data? If it returns a pointer to part of the bigger structure, that should not be freed with free() — it would be freed when you destroy the cjSON object.

    If you take a look at the code for get_object_item() — which is called directly from cJSON_GetObjectItem() in cJSON.c, you will see it returns a pointer into the middle of a cJSON object. You cannot afford to call free() on that return value. You should only call cJSON_Delete() on the complete object. By calling free(msgtype), you are wrecking the integrity of the root data structure — and you probably end up with a double-free problem too.

    If it is available for your platform, use Valgrind to analyze what's going wrong — it will probably tell you. If your system's malloc() implementation has debugging hooks (the version on macOS, for example, does), consider using them.