The correct way to malloc space for a string and then insert characters into this space?

I have two lines: str1 and str2. I want to combine them in space in a 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 a place on the heap when two strings are concatenated? I ask because it seems that strcat will actually add str1 to the end of the space allocated with malloc. It's right? So str1 will appear at position strlen (str1) + strlen (str2) + 1.

The reason I ask is because I use the method above, but I get an error in valgrind: Conditional jump or move depends on uninitialized value (s)

+6
source share
3 answers

In fact, strcat(dest, src) searches for a null byte starting with dest and ending in, and then writes the string src .

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

Instead, 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 very beginning where you want the bytes of both lines to go through and how many there are.

+11
source

You want to do strcpy and then strcat:

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

strcat relies on having a null terminator ('\ 0') to know where to start. If you are just malloc and strcat, this will do some nasty things.

And no, neither strcpy nor strcat will make any implicit allocation or redistribution.

+4
source

I personally would 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); 
+4
source

Source: https://habr.com/ru/post/885619/


All Articles