From 0c8ec0a2fce467b0a2564760f412f0b71538081b Mon Sep 17 00:00:00 2001 From: Niels Lohmann Date: Sat, 4 Jul 2026 14:28:40 +0200 Subject: [PATCH] Assert the destination buffer size in get_bytes get_elements() only receives a raw pointer and cannot know the size of its destination, so the destination-size guarantee is asserted at the caller that owns the buffer: after resizing `result`, assert it has room for `wanted` bytes at `old_size`. Together with the `copied <= wanted` assert at the memcpy, this makes the "destination is large enough" invariant explicit on both sides of the call. Signed-off-by: Niels Lohmann Co-Authored-By: Claude Opus 4.8 --- include/nlohmann/detail/input/binary_reader.hpp | 3 +++ single_include/nlohmann/json.hpp | 3 +++ 2 files changed, 6 insertions(+) diff --git a/include/nlohmann/detail/input/binary_reader.hpp b/include/nlohmann/detail/input/binary_reader.hpp index 5093e032b..205db484b 100644 --- a/include/nlohmann/detail/input/binary_reader.hpp +++ b/include/nlohmann/detail/input/binary_reader.hpp @@ -2970,6 +2970,9 @@ class binary_reader : chunk_size; const std::size_t old_size = result.size(); result.resize(old_size + wanted); + // the destination now has room for `wanted` bytes at offset + // old_size, which is what get_elements() is allowed to write + JSON_ASSERT(result.size() >= old_size + wanted); const std::size_t bytes_read = ia.get_elements(&result[old_size], wanted); chars_read += bytes_read; if (JSON_HEDLEY_UNLIKELY(bytes_read < wanted)) diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index bcc124f14..dea47a62d 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -13176,6 +13176,9 @@ class binary_reader : chunk_size; const std::size_t old_size = result.size(); result.resize(old_size + wanted); + // the destination now has room for `wanted` bytes at offset + // old_size, which is what get_elements() is allowed to write + JSON_ASSERT(result.size() >= old_size + wanted); const std::size_t bytes_read = ia.get_elements(&result[old_size], wanted); chars_read += bytes_read; if (JSON_HEDLEY_UNLIKELY(bytes_read < wanted))