Incorrect result on using toCharArray() or converting a string to array manually

Hi,

I'm using NodeMCU for a project and Arduino 1.8.8. I want to convert a string to char Array. The code and output are as follows.

code:

char ssid[] = "";
char pass[] = "";
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  String answer = "ssid:Moto G (4) 6788aesrhtd5@#$; pass:error$34556jjhjv24";
  extract(answer);
  Serial.println(ssid);
  Serial.println(pass);
}

void extract(String value) {
  String t_ssid = "";
  String t_pass = "";
  int flag = 0;
  int len = value.length();
  for (int i = 0; i < len ; i++) {
    if (value.charAt(i) == ';')
      flag = i;
  }
  t_ssid = value.substring(5, flag);
  t_pass = value.substring(flag + 7, len);
  Serial.print(ssid);
  Serial.println(".");
  Serial.print(pass);
  Serial.println(".");
  Serial.println();
  Serial.println(t_ssid);
  Serial.println(t_pass);
  for (int i = 0; i < t_ssid.length(); i++)
    ssid[i] = t_ssid.charAt(i);
  for (int j = 0; j < t_pass.length(); j++)
    pass[j] = t_pass.charAt(j);
}

void loop() {
  // put your main code here, to run repeatedly:

}

Result:
Screenshot attached herewith. (I've pressed the reset button once.)

Expected Result:

.
.
Moto G (4) 6788aesrhtd5@#$
error$34556jjhjv24

Moto G (4) 6788aesrhtd5@#$
error$34556jjhjv24

I'm pretty much unsure as of why the result is not as expected and also why these ghostly characters are showing up in the serial monitor.

Any help is highly appreciated...

sahebdatta:

char ssid[] = "";

char pass[] = "";

Here you declare two arrays of length 1 (for the null terminator).

sahebdatta:

  for (int i = 0; i < t_ssid.length(); i++)

ssid[i] = t_ssid.charAt(i);
  for (int j = 0; j < t_pass.length(); j++)
    pass[j] = t_pass.charAt(j);

Here you write past the bounds of the arrays, corrupting some random memory and likely resetting your microcontroller.

The difference between char arrays and Strings is that char arrays do not use dynamic memory allocation (and that's why you should never use String). You need to size your arrays large enough to fit the data you are going to write to them (and don't forget +1 for the null terminator).

Hi!

Thanks for the response. The problem is solved after I've declared the size of the char arrays.

char ssid[50];
char pass[50];

But, I'm not getting why these ghostly characters are showing up on resetting the NodeMCU. I'm keeping the serial window open and pressing the reset button on the NodeMCU. After it resets, some ghostly characters appeared and then the required output is obtained.

Any help on this issue?