Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cJSON_Print trapped in an infinite loop when elements are added a certain way #922

Open
dmachinewhisperer opened this issue Jan 14, 2025 · 0 comments

Comments

@dmachinewhisperer
Copy link

Here is a strange behavior of cJSON_Print. When the subtree it is transversing contains a node referenced by an ancestor node, it ends up in an infinite loop. The only way this can happen is if leaf nodes link back to their parents and cJSON_Print tries to transverse this path, resulting in a circular dep. Even this assumption doesn't hold up considering that when the order of placing objects message and system into the messages array is swapped (i.e., adding system before message), printing works perfectly.

Here is a minimal snippet to reproduce this behavior.

#include <stdio.h>
#include <stdlib.h>
#include "../cJSON/cJSON.h"
int main() {
    cJSON *bin = cJSON_CreateArray();
    cJSON *root = cJSON_CreateObject();
    cJSON *system = cJSON_CreateObject();
    cJSON *message = cJSON_CreateObject();
    cJSON *messages = cJSON_CreateArray();

    cJSON_AddItemToArray(bin, root);
    cJSON_AddItemToArray(bin, system);
    cJSON_AddItemToArray(bin, message);
    cJSON_AddItemToArray(messages, message);
    cJSON_AddItemToArray(messages, system);
    cJSON_AddItemToObject(root, "messages", messages);

    char *json_string = cJSON_Print(root);
    printf("%s\n", json_string);
    free(json_string);

cleanup:     
    cJSON_DetachItemFromArray(bin, 0);
    cJSON_DetachItemFromArray(bin, 0);
    cJSON_DetachItemFromArray(bin, 0);    
    cJSON_Delete(root);
    cJSON_Delete(bin);

    return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant