vimalloc
vimalloc

Reputation: 4167

C strcat garbage characters

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

Upvotes: 3

Views: 9205

Answers (3)

BiGYaN
BiGYaN

Reputation: 7159

strcat() assumes the destination to be a valid string, so make it so by adding

*results[0] = '\0';

before you do strcat()

Alternatively try doing these:

strcpy(*results, get_string_1());
strcat(*results, get_string_2());

Lastly, what exactly is happening in this line:

*results = malloc(sizeof(char) * (dir_length + file_length));

Make sure you allocate enough space to results. Ideally it should be:

*results = malloc(sizeof(char) * (s1_length+s2_length+1));

for allocating enough space as s1 and s2 and followed by a terminating '\0' character.

Upvotes: 2

freespace
freespace

Reputation: 16701

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.

Upvotes: 11

0xC0000022L
0xC0000022L

Reputation: 21259

Why do you strcat the first string? Simply copy it. Otherwise it will append to whatever garbage is in the uninitialized memory ...

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

Upvotes: 6

Related Questions