C strcat garbage characters

vimalloc picture vimalloc · Apr 22, 2011 · Viewed 7.6k times · Source

I have a function in C where i am trying to get strings from two different locations (unknown size, could be quiet large) and combine them into one string and return them. If i just print the two strings then I get the correct result, but when I try to combine the strings using strcat I end up with 5 garbage characters and then the result of the combined strings.

Anyone have some advice as to what I am doing wrong? Here is some sample code to demonstrate what I am doing:

static int get_information(char** results)
{
    size_t s1_length;
    size_t s2_length;

    /* DEBUGGING - Prints the correct string */
    printf(get_string_1());
    printf(get_string_2());
    printf("\n");

    /* Allocate memory for new string */
    s1_length = strlen(get_string_1());
    s2_length = strlen(get_string_2());
    *results = malloc(sizeof(char) * (dir_length + file_length));

    if(results == NULL)
        return -1;

    /* Combine the strings */
    strcat(*results, get_string_1());
    strcat(*results, get_string_2());

    /* DEBUGGING - prints 5 garbage characters then the correct string */   
    printf(*results);
    printf("\n");

    return 0;
}

Answer

freespace picture freespace · Apr 22, 2011

strcat needs to find the null terminator in the destination. Your *result points to uninitialised memory, which happens to have a null terminator 5 characters in.

Adding *result[0]='\0'; just before combining the strings should fix it.

Also, you are not allocating enough space for the null terminator in *result.