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
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);
}