Repository navigation
Conversation
When custom hooks leave reallocate unset, ensure() copies the old buffer with memcpy(..., offset + 1). A PrintBuffered prebuffer of 0 can produce a zero-length allocation, so that copy reads one byte the buffer does not own. Skip the copy when length is 0. Issue DaveGamble#1122
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.
Fixes #1122
Root cause
cJSON_PrintBufferedaccepts aprebufferof 0. It then callsallocate(0), which may return a non-null pointer to a zero-byte object, and stores that size in the print buffer'slength.Custom hooks installed with
cJSON_InitHookssetmalloc_fn/free_fnand leavereallocateunset, unless those functions are the raw libcmalloc/freepair.ensure()grows such a buffer by allocating a new one and copying withmemcpy(newbuffer, p->buffer, p->offset + 1). Whenlengthandoffsetare both 0, that copy reads one byte from a zero-sized allocation. The default hooks usereallocand never reach this path.Fix
In the manual growth path of
ensure(), copy from the old buffer only whenp->length > 0. A zero-length buffer owns no bytes.Testing
Windows 11 x64, MSVC 19.51.36256, CMake + Ninja, Debug.
New tests in
tests/misc_tests.c:ensure_should_not_copy_from_zero_length_bufferpoints a zero-length print buffer at a static'X'byte, uses a zero-filling malloc and noreallocatehook, grows it withensure(), and checks the first byte of the new buffer is still 0print_buffered_should_print_with_zero_prebuffer_and_custom_hooksprints42throughcJSON_PrintBufferedwithprebuffer0 and custom hooksBefore:
ensure_should_not_copy_from_zero_length_bufferfails (Expected 0 Was 88),misc_tests31/32.After: passes,
misc_tests32/32 and the full ctest suite 22/22.