Search code examples
cbackslashstring-literals

strcat(dest, "\something") - backslash not showing


I got a problem with C programming string concatenation.

Why strcat(dest, "\something") will not have the backslash copied to dest?

You may wish to follow the example.

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

int main()
{
    char *dest = "";
    char *test = "how \something";
    dest = (char *)malloc((strlen(test) + 1) * sizeof(char));

    strcat(dest, test);
    // Expect to see "how \something", but showed "how something"
    printf("%s\n", dest);

    free(dest);
    return 0;
}

Solution

  • backslash not showing

    Escape it:

       char *test = "how \\something";
    

    The compiler should have warned you about this like this (GCC 4.9.2):

    main.c:8:16: warning: unknown escape sequence: '\s'
       char *test = "how \something";
    

    Also this is not related to strcat().

    To prove this just do

    puts(test);
    

    and receive the same output.


      but showed "how something"
    

    Are you sure? I'd expected

    how omething
    

    Also

    • sizeof (char) is 1 by definition.
    • In C there is no need to cast void-pointers as for example returned by malloc(), nor is it recommended in any way.

    So just do

      dest = malloc(strlen(test) + 1);
    

    or so make the code safe against late changes of dest's type do

      dest = malloc((strlen(test) + 1) * sizeof *dest);
    

    Addition

    As pointed out by anatolyg in this comment you are concatenating to an uninitialised char-array here:

      strcat(dest, test);
    

    This invokes undefined behaviour, which is not good.

    To fix this either do

    • dest[0] = '\0'; or
    • use calloc() instead of malloc()

    to 0-terminate dest and with this make the char-array a C-"string" before using it alike when passing it to strcat().

    • Or just use strcpy() instead of strcat().