strcpy vs strdup

前端 未结 5 1937
抹茶落季
抹茶落季 2020-11-28 02:48

I read that strcpy is for copying a string, and strdup returns a pointer to a new string to duplicate the string.

Could you please explain

5条回答
  •  不知归路
    2020-11-28 03:14

    In the accepted answer, the implementation of strdup is presented as:

    ptr2 = malloc(strlen(ptr1)+1);
    strcpy(ptr2,ptr1);
    

    However, that is somewhat sub-optimal because both strlen and strcpy need to find the length of the string by checking if each character is a \0.

    Using memcpy should be more efficient:

    char *strdup(const char *src) {
        size_t len = strlen(src) + 1;
        char *s = malloc(len);
        if (s == NULL)
            return NULL;
        return (char *)memcpy(s, src, len);
    }
    

提交回复
热议问题