Fix: add depth check to prevent stack overflow in cJSON_Print #984
+10
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
Currently,
cJSON_Parseenforces a depth limit (CJSON_NESTING_LIMIT) to prevent stack overflows during parsing. However, thecJSON_Print(and its internalprint_array/print_objectfunctions) 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_Printresults in a stack overflow (SIGSEGV) rather than failing gracefully.Solution
This PR adds a depth check to
print_arrayandprint_object, mirroring the logic already present incJSON_Parse.if (output_buffer->depth >= CJSON_NESTING_LIMIT)at the beginning ofprint_arrayandprint_object.false, causingcJSON_Printto returnNULLgracefully instead of crashing the application.Impact
Verification
I have tested this with a constructed cJSON object exceeding
CJSON_NESTING_LIMIT.cJSON_PrintreturnsNULL.As discussed with the maintainers, this is submitted as a robustness fix to handle edge cases in internal API usage.