Skip to content

Stack overflow for circular reference #880

@tregua87

Description

@tregua87

I noticed that cJSON does not correctly handle objects with circular references (commit 3249730).
For instance, I can have 3 objects that points each other, e.g., A->B->C->A, the function cJSON_Duplicate enters in a infinite recursions.
Here is a simple example:

#include <cjson/cJSON.h>

#include <stdlib.h>
#include <stdint.h>

int main(int argc, char** argv) {

        cJSON *o = cJSON_CreateArray();
        cJSON *a = cJSON_CreateArray();
        cJSON *b = cJSON_CreateArray();

        cJSON_AddItemToArray(o, a);
        cJSON_AddItemToArray(a, b);
        cJSON_AddItemToArray(b, o);

        cJSON *x = cJSON_Duplicate(o, 1);

        cJSON_Delete(o);
        cJSON_Delete(a);
        cJSON_Delete(b);
        cJSON_Delete(x);

        return 0;
}

The problem seems that cJSON_Duplicate has no way to know if the child has been already processed, line 2773 in my version:

/* Walk the ->next chain for the child. */
    child = item->child;
    while (child != NULL)
    {
        newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain *./
        if (!newchild)
        {
            goto fail;
        }

I would propose a fix but I am not sure how to operate.
I see two possible solutions:

  • avoiding circular references when AddItem is used
  • stop infinite recursion in cJSON_Duplicate or similar.

Can you hint me if you were already aware of this problem, and if you plan to fix it?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions