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

148 views Asked by At

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;
}
2

There are 2 answers

0
Kitswas On BEST ANSWER

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;
}
0
phuclv On

string hasn't been initialized so doesn't contain a valid string. As a result when strcat reads it to find the null terminator it invokes undefined behavior. You must initialize it before using

unsigned char string[100] = { 0 };