Skip to content

Commit

Permalink
WString: change strcpy() to memcpy()
Browse files Browse the repository at this point in the history
It is worth to use memcpy() to avoid extra checks. Furthermore,
it fixes possible issues when copied WString has zero byte stored
intentionally.

copy() methods are protected and always used to copy zero-terminated
strings, so it is safe to copy termination zero byte from source buffer.
  • Loading branch information
mar0x committed Mar 22, 2023
1 parent 0428ad8 commit ef24307
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions cores/arduino/WString.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ String & String::copy(const char *cstr, unsigned int length)
return *this;
}
len = length;
strcpy(buffer, cstr);
memcpy(buffer, cstr, length + 1);
return *this;
}

Expand All @@ -185,7 +185,7 @@ String & String::copy(const __FlashStringHelper *pstr, unsigned int length)
return *this;
}
len = length;
strcpy_P(buffer, (PGM_P)pstr);
memcpy_P(buffer, (PGM_P)pstr, length + 1);
return *this;
}

Expand All @@ -194,7 +194,7 @@ void String::move(String &rhs)
{
if (buffer) {
if (rhs && capacity >= rhs.len) {
strcpy(buffer, rhs.buffer);
memcpy(buffer, rhs.buffer, rhs.len + 1);
len = rhs.len;
rhs.len = 0;
return;
Expand Down Expand Up @@ -266,8 +266,9 @@ unsigned char String::concat(const char *cstr, unsigned int length)
if (!cstr) return 0;
if (length == 0) return 1;
if (!reserve(newlen)) return 0;
strcpy(buffer + len, cstr);
memcpy(buffer + len, cstr, length);
len = newlen;
buffer[len] = 0;
return 1;
}

Expand Down Expand Up @@ -341,7 +342,7 @@ unsigned char String::concat(const __FlashStringHelper * str)
if (length == 0) return 1;
unsigned int newlen = len + length;
if (!reserve(newlen)) return 0;
strcpy_P(buffer + len, (const char *) str);
memcpy_P(buffer + len, (const char *) str, length + 1);
len = newlen;
return 1;
}
Expand Down Expand Up @@ -653,6 +654,7 @@ void String::replace(const String& find, const String& replace)
}
} else if (diff < 0) {
char *writeTo = buffer;
char *end = buffer + len;
while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {
unsigned int n = foundAt - readFrom;
memcpy(writeTo, readFrom, n);
Expand All @@ -662,7 +664,7 @@ void String::replace(const String& find, const String& replace)
readFrom = foundAt + find.len;
len += diff;
}
strcpy(writeTo, readFrom);
memcpy(writeTo, readFrom, end - readFrom + 1);
} else {
unsigned int size = len; // compute size needed for result
while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {
Expand Down

0 comments on commit ef24307

Please sign in to comment.