Problem with char array

The code below prints two lines - the first time numerals and the second time Alphabets.

But if I comment out the line where i clear the array lcdMsgToPrint[] , it does not even print the numerals. Instead it prints some odd characters. Why is that ?

char lcdMsgToPrint[21] ;
char  charVar1[4] ;
char  charVar2[9] ;

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

  strcpy(charVar1, "123");
  strcpy(charVar2, "45678901");
  strcat(lcdMsgToPrint, charVar1);
  strcat(lcdMsgToPrint, charVar2);
  Serial.println(lcdMsgToPrint);

  strcpy(lcdMsgToPrint,"");          // Do not comment this line !!

  strcpy(charVar1, "ABC");
  strcpy(charVar2, "DEFGHIJK");
  strcat(lcdMsgToPrint, charVar1);
  strcat(lcdMsgToPrint, charVar2);
  Serial.println(lcdMsgToPrint);
}

void loop() {
 

}

Just after brief look, the lcdMsgToPrint is not initialized so it may contain random characters. The strcat() appends the string at position of the first zero char occurance. It can be anywhere, even the behind the end of variable with regard to its length. Try to put

lcdMsgToPrint[0] = 0;

somewhere at the begining of setup. Or declare it initialized with zeros.

char lcdMsgToPrint[21] = {0};

@Budvar10

It's a global variable, so should be initialised with zeroes.

@ Ardubit
21 characters is not enough; I counted 11 plus 11, so the arrsy should be 22 plus 1.

@sterretje

Oh yes... you are right. When I did not have that line to flush the lcdMsgToPost [] variable, I was actually trying to copy the 11 Alphabets to the existing Numerals ! And I was expecting that strcpy() will overwrite the existing ... no it copies the new values to the end of the existing ones.

Naturally lcdMsgToPost ran out of space and ended up crashing the MCU.

I tried the same code but with lcdMsgToPost set to 25 elements and found that now the Alphabets were added to the numerals !

Thanks

strcpy does overwrite. It's the strcat that causes the overflow.

sterretje:
@Budvar10

It's a global variable, so should be initialised with zeroes.

Ah, yes you are right!