cinitializationc-stringsuninitialized-constant

Concatenating strings in C: string buffer is not getting cleared after function call


I am trying to concat two strings in the function foo(). I expect the content of string to be abc after both the first and second calls to foo(). The output which I get after the first call is abc but the second call prints abcabc (the third call prints abcabcabc and so on). The string buffer is not getting cleared. It will be helpful if someone could share how it works internally - how the memory is assigned to the string and why the string buffer is not cleared between subsequent calls of the function.

Here is the code I used:

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

int foo(){
    unsigned char string[100];
    unsigned char text[10] = "abc";
    strcat(string, text);
    printf("%s\n", string);
}

int main(){
    foo();
    foo();
    return 0;
}

Solution

  • You forgot to initialize the string variable. This is the reason for all your problems. Trying to access the value of an uninitialized variable causes Undefined behavior.

    Refer to (Why) is using an uninitialized variable undefined behavior?.

    #include <stdio.h>
    #include <string.h>
    
    int foo(){
        unsigned char string[100] = "";
        unsigned char text[10] = "abc";
        strcat(string, text);
        printf("%s\n", string);
    }
    
    int main(){
        foo();
        foo();
        return 0;
    }