Problem with toCharArray

Hello.

I have a problem understanding strange behavior of string.
After ussing toCharArray old string appears in my variables.

Need for:
I get a string variable from Function1 and need this variable for Function2, which acceps char* variable.

What I'm doing wrong?

Thank you for help.

Code which represents the problem:

String st;
char* cha;

void setup() {
  Serial.begin(9600);
  delay(500);

  st="Test";
  Serial.print("st1:");
  Serial.println(st);

  cha="";
  Serial.print("ch1:");
  Serial.println(cha);
  Serial.println("");

  st.toCharArray(cha,st.length()+1);//PROBLEM LINE
  Serial.print("cha2:");
  Serial.println(cha);
  
  cha="Mhh";
  Serial.print("cha3:");
  Serial.println(cha);

  st="";
  Serial.print("st2:");
  Serial.println(st);
  Serial.println("");
}

void loop() {

}

Serial monitor with problem line (NOT OK):

st1:Test
ch1:

cha2:Test
Testcha3:Mhh
Testst2:
TestTest
Test

Serial monitor without problem line (OK):

st1:Test
ch1:

cha2:
cha3:Mhh
st2:

You need to allocate space. cha is currently a pointer basically pointing to nowhere. Next it points to an empty string (1 byte) and next you dump N bytes in there overwriting part of uour memory.

Just use something like char cha[100] instead of char *cha.

And even better, get rid if String (capital S) and work with the cha array directly.

Thank you very much.

It is not a good idea to use the String (capital S) class on an Arduino as it can cause memory corruption in the small memory on an Arduino. Just use cstrings - char arrays terminated with 0.

...R

Strings = evil

1 Like