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.
  • Loading branch information
mar0x committed Mar 20, 2023
1 parent 0428ad8 commit 1cf02f6
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions cores/arduino/WString.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,8 @@ String & String::copy(const char *cstr, unsigned int length)
return *this;
}
len = length;
strcpy(buffer, cstr);
memcpy(buffer, cstr, length);
buffer[len] = 0;
return *this;
}

Expand All @@ -185,7 +186,8 @@ 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);
buffer[len] = 0;
return *this;
}

Expand All @@ -194,7 +196,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 +268,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,8 +344,9 @@ 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);
len = newlen;
buffer[len] = 0;
return 1;
}

Expand Down Expand Up @@ -653,6 +657,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 +667,8 @@ void String::replace(const String& find, const String& replace)
readFrom = foundAt + find.len;
len += diff;
}
strcpy(writeTo, readFrom);
memcpy(writeTo, readFrom, end - readFrom);
buffer[len] = 0;
} else {
unsigned int size = len; // compute size needed for result
while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {
Expand Down

0 comments on commit 1cf02f6

Please sign in to comment.