Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcpy vs strdup

Tags:

c

strdup

strcpy

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?

like image 506
johan Avatar asked Dec 24 '12 10:12

johan


People also ask

What's the difference between strdup and strcpy?

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.

Why do we use strdup?

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.

Which is better strcpy or memcpy?

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 .

What can I use instead of strdup in C?

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.


1 Answers

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.

like image 179
Abdul Muheedh Avatar answered Oct 07 '22 22:10

Abdul Muheedh