-
-
Notifications
You must be signed in to change notification settings - Fork 7k
Make String::move of an invalidated String result in an invalidated String #5127
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
✅ Build completed. Please test this code using one of the following: ⬇️ http://downloads.arduino.cc/javaide/pull_requests/arduino-PR-5127-BUILD-573-linux32.tar.xz ℹ️ The |
@@ -193,7 +193,7 @@ String & String::copy(const __FlashStringHelper *pstr, unsigned int length) | |||
void String::move(String &rhs) | |||
{ | |||
if (buffer) { | |||
if (capacity >= rhs.len) { | |||
if (rhs && capacity >= rhs.len) { | |||
strcpy(buffer, rhs.buffer); | |||
len = rhs.len; | |||
rhs.len = 0; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wonder why this copy code is even here in the first place? Why not just always take over the buffer of rhs? That would be faster, and the only downside is that the buffer pointer for this string changes (but nobody should rely on it anyway)?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@matthijskooijman good question!
Maybe it's to avoid memory fragmentation?
@PaulStoffregen @damellis @cmaglie do you have any thoughts on this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the only downside is that the buffer pointer for this string changes (but nobody should rely on it anyway)?
there is the c_str()
operator and there are PR that pushes for using it outside the string class also for writing :-)
Maybe it's to avoid memory fragmentation?
I guess that's the reason, move
is called from the c++11 move-constructor, so it's probably better to keep the original (rvalue) allocation whenever possible to avoid making "holes".
See arduino/Arduino#5127 Signed-off-by: Frederic.Pillon <[email protected]>
See arduino/Arduino#5127 Signed-off-by: Frederic.Pillon <[email protected]>
Currently the sketch below prints out:
However, I expect the output to be:
because the
blah()
function returns an invalidated String (NULL buffer, zero length). However, since theString s;
is equivalent toString s("")
,s
's buffer isrealloc(NULL, 0)
resulting in a valid buffer.