diff --git a/include/json/value.h b/include/json/value.h index 14c4129..229aa9e 100644 --- a/include/json/value.h +++ b/include/json/value.h @@ -518,7 +518,7 @@ private: LargestUInt uint_; double real_; bool bool_; - char* string_; + char* string_; // actually ptr to unsigned, followed by str ObjectValues* map_; } value_; ValueType type_ : 8; diff --git a/src/lib_json/json_value.cpp b/src/lib_json/json_value.cpp index 3378e76..eae87db 100644 --- a/src/lib_json/json_value.cpp +++ b/src/lib_json/json_value.cpp @@ -100,6 +100,28 @@ static inline char* duplicateStringValue(const char* value, return newString; } +/* Record the length as a prefix. + */ +static inline char* duplicatePrefixedStringValue( + const char* value, + unsigned int length = unknown) +{ + if (length == unknown) + length = (unsigned int)strlen(value); + + // Avoid an integer overflow in the call to malloc below by limiting length + // to a sane value. + if (length >= (unsigned)Value::maxInt) + length = Value::maxInt - 1; + + char* newString = static_cast(malloc(length + 1)); + JSON_ASSERT_MESSAGE(newString != 0, + "in Json::Value::duplicateStringValue(): " + "Failed to allocate string value buffer"); + memcpy(newString, value, length); + newString[length] = 0; + return newString; +} /** Free the string duplicated by duplicateStringValue(). */ static inline void releaseStringValue(char* value) { free(value); }