Fix memory leak in cJSON_AddItemReferenceToObject on string alloc failure#1008
Open
icsfy wants to merge 1 commit intoDaveGamble:masterfrom
Open
Fix memory leak in cJSON_AddItemReferenceToObject on string alloc failure#1008icsfy wants to merge 1 commit intoDaveGamble:masterfrom
icsfy wants to merge 1 commit intoDaveGamble:masterfrom
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Bug description
There is a potential memory leak in
cJSON_AddItemReferenceToObjectthat occurs in low-memory situations. If the allocation for the key string fails insideadd_item_to_object, the memory dynamically allocated for thereferenceobject is leaked.Code analysis
In
cJSON.c,cJSON_AddItemReferenceToObjectis implemented via chained function calls:If we look at
add_item_to_object()whenconstant_keyisfalse:If
cJSON_strdupreturnsNULLdue to out-of-memory, it returnsfalse. However, theitem(which was freshly allocated bycreate_reference) is neither freed inadd_item_to_object, nor in the parent functioncJSON_AddItemReferenceToObject. The pointer is lost, resulting in a memory leak.Contrast this with
cJSON_AddNullToObjectand similar functions which safely capture the created node and callcJSON_Delete(null)ifadd_item_to_objectreturns false.Proposed Fix
The fix is to separate the node creation from the attachment, and explicitly manage its lifecycle upon failure: