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
?
Difference between strdup() and strcpy()The function strcpy() will not allocate the memory space to copy. A pointer to the string to copy and a pointer to place to copy it to should be given. The function strdup() will occupy / grab itself the memory space for copying the string to.
Writing to a constant string will produce unexpected results and often crashes. The strdup function fixes the problem because it creates a mutable copy which is placed into a slot expecting a mutable string.
memcpy should be used if you know well that source contain other than character. for encrypted data or binary data, memcpy is ideal way to go. strcpy is deprecated, so use strncpy .
syntax: char *strndup(const char *s, size_t n); This function is similar to strdup(), but copies at most n bytes. Note: If s is longer than n, then only n bytes are copied, and a NULL ('\0') is added at the end.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With