utils: Truncate oversized CString allocations rather than overflowing internal length logic
This commit is contained in:
committed by
Mathias Agopian
parent
2cdff4b521
commit
8f11927aae
@@ -66,11 +66,15 @@ public:
|
||||
|
||||
// Allocates memory and appends a null. This constructor can be used to hold arbitrary data
|
||||
// inside the string (i.e. it can contain nulls or non-ASCII encodings).
|
||||
// Note: If length exceeds the 32-bit maximum capacity of CString, it will be safely
|
||||
// truncated to std::numeric_limits<size_type>::max().
|
||||
CString(const char* cstr, size_t length);
|
||||
|
||||
// Allocates memory for a string of size length plus space for the null terminating character.
|
||||
// Also initializes the memory to 0. This constructor can be used to hold arbitrary data
|
||||
// inside the string.
|
||||
// Note: If length exceeds the 32-bit maximum capacity of CString, it will be safely
|
||||
// truncated to std::numeric_limits<size_type>::max().
|
||||
explicit CString(size_t length);
|
||||
|
||||
// Conversion from std::string_view
|
||||
|
||||
+12
-10
@@ -61,24 +61,26 @@ void CString::do_tracking(bool ctor) {
|
||||
UTILS_NOINLINE
|
||||
CString::CString(const char* cstr, size_t const length) {
|
||||
track(true);
|
||||
if (length && cstr) {
|
||||
Data* const p = static_cast<Data*>(std::malloc(sizeof(Data) + length + 1));
|
||||
p->length = size_type(length);
|
||||
size_t const len = std::min(length, (size_t)std::numeric_limits<size_type>::max());
|
||||
if (len && cstr) {
|
||||
Data* const p = static_cast<Data*>(std::malloc(sizeof(Data) + len + 1));
|
||||
p->length = size_type(len);
|
||||
mCStr = reinterpret_cast<value_type*>(p + 1);
|
||||
// we don't use memcpy here to avoid a call to libc, the generated code is pretty good.
|
||||
std::uninitialized_copy_n(cstr, length, mCStr);
|
||||
mCStr[length] = '\0';
|
||||
std::uninitialized_copy_n(cstr, len, mCStr);
|
||||
mCStr[len] = '\0';
|
||||
}
|
||||
}
|
||||
|
||||
CString::CString(size_t const length) {
|
||||
track(true);
|
||||
if (length) {
|
||||
Data* const p = static_cast<Data*>(std::malloc(sizeof(Data) + length + 1));
|
||||
p->length = size_type(length);
|
||||
size_t const len = std::min(length, (size_t)std::numeric_limits<size_type>::max());
|
||||
if (len) {
|
||||
Data* const p = static_cast<Data*>(std::malloc(sizeof(Data) + len + 1));
|
||||
p->length = size_type(len);
|
||||
mCStr = reinterpret_cast<value_type*>(p + 1);
|
||||
std::fill_n(mCStr, length, 0);
|
||||
mCStr[length] = '\0';
|
||||
std::fill_n(mCStr, len, 0);
|
||||
mCStr[len] = '\0';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user