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

后端 未结 3 888
太阳男子
太阳男子 2020-12-06 07:11

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(strl         


        
3条回答
  •  长情又很酷
    2020-12-06 07:49

    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.

提交回复
热议问题