Search code examples
carraysstringconcatenation

how to overcome undefined behavior in strings concatenation?


I want to concatenate strings in c. Therefore I wrote the following code:

#include <stdio.h>
#include <string.h>


int main () {
    char str1[20], str2[20];
    int i=0;
    
    scanf("%20s",str1);
    getchar();
    scanf("%20s",str2);
    getchar();
    char str3[strlen(str1)+strlen(str2)];

    for(i=0; str1[i]; i++){
        str3[i]=str1[i];
    }
    
    for(i=0; str2[i]; i++){
        str3[strlen(str1)+i]=str2[i];
    }
    
    printf("\nSum is: %s\n", str3);
    
    return 0;
}

Why do I get random characters at the end of the sum str3? I know there are a function to do that, but I wanted to do it an elementary way.


Solution

  • Because you are invoking undefined behavior by having printf() read out-of-bounds of str3.

    You must

    1. Allocate one more element for terminating null character.
      i.e. char str3[strlen(str1)+strlen(str2)]; should be char str3[strlen(str1)+strlen(str2)+1];
    2. Put a terminating null character at the end of the resulting string.
      i.e. Add str3[strlen(str1)+strlen(str2)] = '\0'; before the printf() statement.