Skip to content

Conversation

@liloler
Copy link

@liloler liloler commented Feb 2, 2026

Problem

Currently, cJSON_Parse enforces a depth limit (CJSON_NESTING_LIMIT) to prevent stack overflows during parsing. However, the cJSON_Print (and its internal print_array / print_object functions) does not check this limit.

If a cJSON structure is constructed with a depth exceeding the stack size (e.g., via internal API manipulation or deep recursion), calling cJSON_Print results in a stack overflow (SIGSEGV) rather than failing gracefully.

Solution

This PR adds a depth check to print_array and print_object, mirroring the logic already present in cJSON_Parse.

  • Added a check: if (output_buffer->depth >= CJSON_NESTING_LIMIT) at the beginning of print_array and print_object.
  • If the depth limit is reached, the function now returns false, causing cJSON_Print to return NULL gracefully instead of crashing the application.

Impact

  • Safety: Prevents crashes when printing deeply nested objects.
  • Consistency: Aligns the behavior of the printer with the parser regarding nesting limits.
  • Performance: Minimal impact (two integer comparisons per node).

Verification

I have tested this with a constructed cJSON object exceeding CJSON_NESTING_LIMIT.

  • Before: Segmentation fault.
  • After: cJSON_Print returns NULL.

As discussed with the maintainers, this is submitted as a robustness fix to handle edge cases in internal API usage.

@PeterAlfredLee
Copy link
Contributor

Looks good to me.

@PeterAlfredLee
Copy link
Contributor

PeterAlfredLee commented Feb 7, 2026

This safety improvement looks good. However, introducing CJSON_NESTING_LIMIT (default 1000) to cJSON_Print is a behavior change that could impact downstream consumers who process deeply nested JSON. Any logic relying on unbounded recursion may now fail.

If anyone expects deeper nesting, please flag it here so we can adjust the default.

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

Successfully merging this pull request may close these issues.

2 participants