strcpy vs strdup

johan picture johan · Dec 24, 2012 · Viewed 74.4k times · Source

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 what cases do you prefer to use strcpy and what cases do you prefer to use strdup?

Answer

Abdul Muheedh picture Abdul Muheedh · Dec 24, 2012

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.