Skip to content

Commit 79b6489

Browse files
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 16ca3c9 commit 79b6489

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

Diff for: api/String.cpp

+3-3
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ String & String::copy(const char *cstr, unsigned int length)
176176
return *this;
177177
}
178178
len = length;
179-
strcpy(buffer, cstr);
179+
memcpy(buffer, cstr, length);
180180
return *this;
181181
}
182182

@@ -196,7 +196,7 @@ void String::move(String &rhs)
196196
{
197197
if (buffer) {
198198
if (rhs && capacity >= rhs.len) {
199-
strcpy(buffer, rhs.buffer);
199+
memcpy(buffer, rhs.buffer, rhs.len);
200200
len = rhs.len;
201201
rhs.len = 0;
202202
return;
@@ -268,7 +268,7 @@ unsigned char String::concat(const char *cstr, unsigned int length)
268268
if (!cstr) return 0;
269269
if (length == 0) return 1;
270270
if (!reserve(newlen)) return 0;
271-
strcpy(buffer + len, cstr);
271+
memcpy(buffer + len, cstr, length);
272272
len = newlen;
273273
return 1;
274274
}

0 commit comments

Comments
 (0)