strcpy vs strdup

strcpy(ptr2, ptr1) is equivalent to while(*ptr2++ = *ptr1++)

where as strdup is equivalent to

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

(memcpy version might be more efficient)

So if you want the string which you have copied to be used in another function (as it is created in heap section) you can use strdup, else strcpy is enough.

Leave a Comment