Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to malloc space for a string and then insert characters into that space?

Tags:

c

I have two strings, str1 and str2. I want the concatenation of them on a space in the heap. I malloc space for them using:

char *concat = (char*) malloc(strlen(str1) + strlen(str2) + 1);

Can I just do:

strcat(concat, str1);
strcat(concat, str2);

And concat will give me the place on the heap with the two strings concatted? I am asking because it seems that strcat would actually add the str1 to the end of the space allocated using malloc. Is this correct? So, then, str1 would appear at position strlen(str1) + strlen(str2) + 1.

The reason that I am asking is that I am using the method above, but I am getting an error in valgrind: Conditional jump or move depends on uninitialised value(s)

like image 933
Kelp Avatar asked Apr 10 '11 20:04

Kelp


3 Answers

What strcat(dest, src) actually does is search for the a null byte starting at dest and going forward, and then write the src string there.

After malloc, the contents of memory are undefined, so your current code could do any number of things, most of them incorrect. If you do concat[0] = 0 before the strcat's, then your code works but will have to search for the length of str1 three times -- once for strlen, again for the first strcat, and last for the second strcat.

Instead though, I recommend using memcpy:

size_t len1 = strlen(str1), len2 = strlen(str2);
char *concat = (char*) malloc(len1 + len2 + 1);

memcpy(concat, str1, len1);
memcpy(concat+len1, str2, len2+1);

This takes advantage of the fact that you know from the start where you want the bytes of both strings to go, and how many there are.

like image 149
Walter Mundt Avatar answered Oct 20 '22 00:10

Walter Mundt


You want to do a strcpy and then a strcat:

strcpy(concat, str1);
strcat(concat, str2);

strcat relies on there being a null terminator ('\0') to know where to begin. If you just malloc and strcat, it's going to do some nasty things.

And no, neither strcpy nor strcat will do any kind of implicit allocation or reallocation.

like image 31
Chris Eberle Avatar answered Oct 20 '22 00:10

Chris Eberle


I would personally do the following:

size_t length = strlen(str1) + strlen(str2) + 1;
char *concat = malloc(sizeof(char) * length);

if(concat == NULL)
{
    // error
}

snprintf(concat, length, "%s%s", str1, str2);
like image 27
Tim Cooper Avatar answered Oct 19 '22 23:10

Tim Cooper