简体   繁体   中英

Concatenate two strings using memcpy

I am trying to make a function that concatenates two strings without using strncat / strcat in C. I have this, but it gives a segfault error. What am I doing wrong?

char *concat(char *str1, char *str2) {
    memcpy(str1 + strlen(str1) - 1, str2, strlen(str2) + 1);
    return str1;
}

This is not homework. It's for the C toolchain for TI-84 Plus CE and strncat doesn't work for me in this function. str1 will be a string literal. str2 will be variable.

You have to ensure that str1 points to a memory location big enough to receive the entire result :

char *concat(char const*str1, char const*str2) {
   size_t const l1 = strlen(str1) ;
   size_t const l2 = strlen(str2) ;

    char* result = malloc(l1 + l2 + 1);
    if(!result) return result;
    memcpy(result, str1, l1) ;
    memcpy(result + l1, str2, l2 + 1);
    return result;
}

Additionally, you should add error checking, as much as possible, at least some assert(str1) ; assert(str2) ; assert(str1) ; assert(str2) ; ...

Your function implements strcat in a simple and straight forward way with the same restrictions, but it has a bug: you are copying the contents of str2 one byte after the end of the string in str1 . Remove the + 1 in the first argument to memcpy . Note that you can make str2 a const char * as you are not modifying the contents of the array it points to.

char *concat(char *str1, const char *str2) {
    memcpy(str1 + strlen(str1), str2, strlen(str2) + 1);
    return str1;
}

If the destination array is a string literal , you cannot use this approach as attempting to modify string literals has undefined behavior. You should first copy the string literal into an array large enough to accommodate both strings and the null terminator.

You can try this:

char *str1="hello";
char *str2=" world";
char *str3;

str3=(char *) malloc (11 *sizeof(char));
memcpy(str3,str1,5);
memcpy(str3+strlen(str1),str2,6);

printf("%s + %s = %s",str1,str2,str3);
free(str3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM