Skip to content

Commit 14c0887

Browse files
matthijskooijmanaentinger
authored andcommitted
Make string concat, copy and move work on non-terminated strings
Previously, these methods took a nul-terminated string and appended it to the current buffer. The length argument (or length of the passed String object) was used to allocate memory, but was not used when actually copying the string. This meant that: - If the passed length was too short, or the string passed in was not nul-terminated, the buffer would overflow. - If the string passed in contained embedded nul characters (i.e, among the first length characters), any characters after the embedded nul would not be copied (but len would be updated to indicate they were). In practice, neither of the above would occur, since the length passed is always the known length of the string, usually as returned by strlen. However, to make this method public, and to allow using this concat method to pass in strings that are not nul-terminated, it should be changed to be more robust. This commit changes the method to use memcpy instead of strcpy, copying exactly the number of bytes passed in. For the current calls to this method, which pass a nul-terminated string, without embedded nul characters and a correct length, this behaviour should not change. However, this concat method can now also be used in the two cases mentioned above. Non-nul-terminated strings now work as expected and for strings with embedded newlines the entire string is copied as-is, instead of leaving uninitialized memory after the embedded nul byte. Note that a lot of operations will still only see the string up to the embedded nul byte, but that's not really fixable unless we reimplement functions like strcmp.
1 parent 6876081 commit 14c0887

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

api/String.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ String & String::copy(const char *cstr, unsigned int length)
178178
return *this;
179179
}
180180
len = length;
181-
strcpy(buffer, cstr);
181+
memcpy(buffer, cstr, length);
182182
return *this;
183183
}
184184

@@ -198,7 +198,7 @@ void String::move(String &rhs)
198198
{
199199
if (buffer) {
200200
if (rhs && capacity >= rhs.len) {
201-
strcpy(buffer, rhs.buffer);
201+
memcpy(buffer, rhs.buffer, rhs.len);
202202
len = rhs.len;
203203
rhs.len = 0;
204204
return;
@@ -270,7 +270,7 @@ unsigned char String::concat(const char *cstr, unsigned int length)
270270
if (!cstr) return 0;
271271
if (length == 0) return 1;
272272
if (!reserve(newlen)) return 0;
273-
strcpy(buffer + len, cstr);
273+
memcpy(buffer + len, cstr, length);
274274
len = newlen;
275275
return 1;
276276
}

0 commit comments

Comments
 (0)