Skip to content

Commit 1cf02f6

Browse files
committed
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.
1 parent 0428ad8 commit 1cf02f6

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

cores/arduino/WString.cpp

+12-6
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,8 @@ String & String::copy(const char *cstr, unsigned int length)
174174
return *this;
175175
}
176176
len = length;
177-
strcpy(buffer, cstr);
177+
memcpy(buffer, cstr, length);
178+
buffer[len] = 0;
178179
return *this;
179180
}
180181

@@ -185,7 +186,8 @@ String & String::copy(const __FlashStringHelper *pstr, unsigned int length)
185186
return *this;
186187
}
187188
len = length;
188-
strcpy_P(buffer, (PGM_P)pstr);
189+
memcpy_P(buffer, (PGM_P)pstr, length);
190+
buffer[len] = 0;
189191
return *this;
190192
}
191193

@@ -194,7 +196,7 @@ void String::move(String &rhs)
194196
{
195197
if (buffer) {
196198
if (rhs && capacity >= rhs.len) {
197-
strcpy(buffer, rhs.buffer);
199+
memcpy(buffer, rhs.buffer, rhs.len + 1);
198200
len = rhs.len;
199201
rhs.len = 0;
200202
return;
@@ -266,8 +268,9 @@ unsigned char String::concat(const char *cstr, unsigned int length)
266268
if (!cstr) return 0;
267269
if (length == 0) return 1;
268270
if (!reserve(newlen)) return 0;
269-
strcpy(buffer + len, cstr);
271+
memcpy(buffer + len, cstr, length);
270272
len = newlen;
273+
buffer[len] = 0;
271274
return 1;
272275
}
273276

@@ -341,8 +344,9 @@ unsigned char String::concat(const __FlashStringHelper * str)
341344
if (length == 0) return 1;
342345
unsigned int newlen = len + length;
343346
if (!reserve(newlen)) return 0;
344-
strcpy_P(buffer + len, (const char *) str);
347+
memcpy_P(buffer + len, (const char *) str, length);
345348
len = newlen;
349+
buffer[len] = 0;
346350
return 1;
347351
}
348352

@@ -653,6 +657,7 @@ void String::replace(const String& find, const String& replace)
653657
}
654658
} else if (diff < 0) {
655659
char *writeTo = buffer;
660+
char *end = buffer + len;
656661
while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {
657662
unsigned int n = foundAt - readFrom;
658663
memcpy(writeTo, readFrom, n);
@@ -662,7 +667,8 @@ void String::replace(const String& find, const String& replace)
662667
readFrom = foundAt + find.len;
663668
len += diff;
664669
}
665-
strcpy(writeTo, readFrom);
670+
memcpy(writeTo, readFrom, end - readFrom);
671+
buffer[len] = 0;
666672
} else {
667673
unsigned int size = len; // compute size needed for result
668674
while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {

0 commit comments

Comments
 (0)