Search code examples
cstringsegmentation-faultstring-concatenationstrcat

Append ' before and after char[] in C


I am trying to append single quotes before and after a char array. Following is the code I am trying:

static const char str[] = "select * from name";
STATICF boolean test(){
   char[] key = "1234";
   strcat(str,(const char *)"\'");
   strcat(str,key);
   strcat(str,(const char *)"\'");
}

It does not work as I get segmentation fault. How can I fix this?


Solution

  • strcat(str,(const char *)"\'");
    strcat(str,key);
    strcat(str,(const char *)"\'");
    

    str needs to be big enough to hold the whole concatenated result string, plus \0 to terminate the string. This isn´t the case at your example with the declaration of str as:

    static const char str[] = "select * from name";
    

    with str to hold only the size of the old string plus \0. Thus, trying to append more characters causes the segmentation fault.


    Try to declare str with a fixed size, large enough to hold the result string (the old string of select * from name + \' + 1234 + \' + the terminating \0 which shall be 25 characters in total if I´d counted right).

    str needs to be non-constant to change the value of str by the way, so omit static const.

    Also omit the cast of (const char *); and replace "\'" with "'".

    The result is like the following:

    char str[25];
    strcpy(str,"select * from name");
    STATICF boolean test(){
       char key[] = "1234";
       strcat(str,"'");
       strcat(str,key);
       strcat(str,"'");
    }