Search code examples
cstringcharconcatenationstrcat

strcat concat a char onto a string?


Using GDB, I find I get a segmentation fault when I attempt this operation:

strcat(string,&currentChar);

Given that string is initialized as

char * string = "";

and currentChar is

char currentChar = 'B';

Why does this result in a segmentation fault?

If strcat can't be used for this, how else can I concat a char onto a string?


Solution

  • Because &currentChar is not a string, it doesn't finish with \0 character. You should define B as char *currentChar = 'B';. Also according to http://www.cplusplus.com/reference/clibrary/cstring/strcat string should have enough space to hold the result string (2 bytes in this case), but it is only 1 byte.

    Or if you want to use char then you can do something like (depending of your code):

    char string[256];
    ...
    
    char currentChar = 'B';
    size_t cur_len = strlen(string);
    if(cur_len < 254) {
        string[cur_len] = currentChar;
        string[cur_len+1] = '\0';
    }
    else
        printf("Not enough space");