From 1cf02f6d8fea593b83b9bdb96a75e3a9ca402b93 Mon Sep 17 00:00:00 2001 From: Max Romanov Date: Mon, 20 Mar 2023 14:44:05 +0300 Subject: [PATCH] WString: change strcpy() to memcpy() It is worth to use memcpy() to avoid extra checks. Furthermore, it fixes possible issues when copied WString has zero byte stored intentionally. --- cores/arduino/WString.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/cores/arduino/WString.cpp b/cores/arduino/WString.cpp index 043fda7c0..f28e044ac 100644 --- a/cores/arduino/WString.cpp +++ b/cores/arduino/WString.cpp @@ -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; } @@ -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; } @@ -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; @@ -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; } @@ -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; } @@ -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); @@ -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) {