Skip to content

problem of copying a String with nul byte in the middle #4796

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

Open
Dvanoska opened this issue Apr 1, 2016 · 3 comments
Open

problem of copying a String with nul byte in the middle #4796

Dvanoska opened this issue Apr 1, 2016 · 3 comments
Labels
Component: Core Related to the code for the standard Arduino API Type: Bug

Comments

@Dvanoska
Copy link

Dvanoska commented Apr 1, 2016

After uploading my sketch (using Arduino 1.6.8 and Arduino Uno),

void loop()
{

  String str1 = "ACDEFG";
  String str2 = "HIP";

  String str3 = str1 + '\0' + str2;

  Serial.println(str1);
  Serial.println(str1.length());
  Serial.println(str2);
  Serial.println(str2.length());
  Serial.println(str3);
  Serial.println(str3.length());
  Serial.println();
  delay(10000);
}

I’m expecting to get as a result something like this:

ACDEFG
6
HIP
3
ACDEFG0HIP
10

But the result is:

ACDEFG
6
HIP
3
ACDEFG `ah
10

I.e. if I understand the problem correctly the String object keeps the right length of str3, but while copying the ‘\0’ it decides the string is over, but it’s not. So in str3 I get right symbols before ‘\0’ and some garbage after.

@matthijskooijman
Copy link
Collaborator

See also #1936, which I believe fixes this (but is probably outdated and needs a rebase, which I'll happily do if anyone intends to merge it).

@cousteaulecommandant
Copy link
Contributor

Might this be because String::concat(cstr, len) uses strcpy() instead of memcpy()? strcpy() is not precisely good at copying char buffers which might contain null bytes...
(Also if memcpy is used instead it wouldn't be necessary to create a 2-byte array and adding a \0 for String::concat(char))

@matthijskooijman
Copy link
Collaborator

@cousteaulecommandant, Yeah, that's exactly one of the things changed by #1936, see c63b861

@per1234 per1234 added the Component: Core Related to the code for the standard Arduino API label Jul 4, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Component: Core Related to the code for the standard Arduino API Type: Bug
Projects
None yet
Development

No branches or pull requests

4 participants