Skip to content

Commit cdea825

Browse files
committed
Assert that String() and Key() are given null-terminated strings
Assert in case users attempt to pass a char array to String() or Key() that is not null terminated; that is not the intended use of the API. Null terminate your string buffers.
1 parent 61f8c4e commit cdea825

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

include/rapidjson/prettywriter.h

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,9 +193,15 @@ class PrettyWriter : public Writer<OutputStream, SourceEncoding, TargetEncoding,
193193

194194
//! The compiler can give us the length of quoted strings for free.
195195
template <typename T, size_t N>
196-
bool String(const T (&str)[N], RAPIDJSON_ENABLEIF((internal::IsSame<Ch, T>))) { return String(str, N-1); }
196+
bool String(const T (&str)[N], RAPIDJSON_ENABLEIF((internal::IsSame<Ch, T>))) {
197+
RAPIDJSON_ASSERT(str[N-1] == '\0'); // you must pass in a null-terminated string (quoted constant strings are always null-terminated)
198+
return String(str, N-1);
199+
}
197200
template <typename T, size_t N>
198-
bool Key(const T (&str)[N], RAPIDJSON_ENABLEIF((internal::IsSame<Ch, T>))) { return Key(str, N-1); }
201+
bool Key(const T (&str)[N], RAPIDJSON_ENABLEIF((internal::IsSame<Ch, T>))) {
202+
RAPIDJSON_ASSERT(str[N-1] == '\0'); // you must pass in a null-terminated string (quoted constant strings are always null-terminated)
203+
return Key(str, N-1);
204+
}
199205

200206
//@}
201207

include/rapidjson/writer.h

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -257,9 +257,15 @@ class Writer {
257257

258258
//! The compiler can give us the length of quoted strings for free.
259259
template <typename T, size_t N>
260-
bool String(const T (&str)[N], RAPIDJSON_ENABLEIF((internal::IsSame<Ch, T>))) { return String(str, N-1); }
260+
bool String(const T (&str)[N], RAPIDJSON_ENABLEIF((internal::IsSame<Ch, T>))) {
261+
RAPIDJSON_ASSERT(str[N-1] == '\0'); // you must pass in a null-terminated string (quoted constant strings are always null-terminated)
262+
return String(str, N-1);
263+
}
261264
template <typename T, size_t N>
262-
bool Key(const T (&str)[N], RAPIDJSON_ENABLEIF((internal::IsSame<Ch, T>))) { return Key(str, N-1); }
265+
bool Key(const T (&str)[N], RAPIDJSON_ENABLEIF((internal::IsSame<Ch, T>))) {
266+
RAPIDJSON_ASSERT(str[N-1] == '\0'); // you must pass in a null-terminated string (quoted constant strings are always null-terminated)
267+
return Key(str, N-1);
268+
}
263269

264270
//@}
265271

0 commit comments

Comments
 (0)