Strcpy vs strdup

I read that strcpy is for copying a string, and strdup returns a pointer to a new string to duplicate the string.

Could you explain which cases you prefer to use strcpy and which cases you prefer to use strdup ?

+59
c strcpy strdup
Dec 24
source share
5 answers

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

where as strdup is equivalent

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

( memcpy version might be more efficient)

So, if you want the line you copied to be used in another function (since it was created in the heap section), you can use strdup, otherwise strcpy is enough.

+89
Dec 24
source share

The strcpy and strncpy functions are part of the C standard library and work with existing memory. That is, you must provide a memory in which functions copy string data, and as a result, you must have your own ways of knowing how much memory you need.

Depending on the constant, strdup is a Posix function and performs dynamic memory allocation for you. It returns a pointer to the newly allocated memory to which it copied the string. But you are now responsible for this memory and should ultimately free it.

This makes strdup one of the "hidden malloc " convenience functions, and this is apparently also why it is not part of the standard library. As long as you use the standard library, you know what you should call free for each malloc / calloc . But functions like strdup introduce hidden malloc , and you should treat it like malloc does for memory management. (Other such hidden selection features are GCC abi::__cxa_demangle() .) Beware!

+38
Dec 24
source share

strdup allocates memory for a new line on the heap, when using strcpy (or the safer strncpy varient), I can copy the line to the previously allocated memory on either the heap or the stack.

+12
Dec 24
source share

In the accepted answer, strdup implementation strdup presented as:

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

However, this is somewhat suboptimal, because both strlen and strcpy need to find the length of the string by checking if each character is \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); } 
+6
Jun 25 '16 at 10:01
source share

char *strdup(char *pszSrch) ;

strdup will allocate the memory size of the original string. If the storage distribution is successful, the original row is copied to the duplicate row.

strdup d return NULL on failure. If no memory is allocated, copying fails with strdup return NULL .

0
Feb 07 '14 at 4:52
source share



All Articles