What is the purpose of the strdup()
function in C?
相关问题
- Multiple sockets for clients to connect to
- Keeping track of variable instances
- What is the best way to do a search in a large fil
- How to get the maximum of more than 2 numbers in V
- glDrawElements only draws half a quad
No point repeating the other answers, but please note that
strdup()
can do anything it wants from a C perspective, since it is not part of any C standard. It is however defined by POSIX.1-2001.strdup
andstrndup
are defined in POSIX compliant systems as:The strdup() function allocates sufficient memory for a copy of the string
str
, does the copy, and returns a pointer to it.The pointer may subsequently be used as an argument to the function
free
.If insufficient memory is available,
NULL
is returned anderrno
is set toENOMEM
.The strndup() function copies at most
len
characters from the stringstr
always null terminating the copied string.Maybe the code is a bit faster than with
strcpy()
as the\0
char doesn't need to be searched again (It already was withstrlen()
).strdup() does dynamic memory allocation for the character array including the end character '\0' and returns the address of the heap memory:
So, what it does is give us another string identical to the string given by its argument, without requiring us to allocate memory. But we still need to free it, later.
Exactly what it sounds like, assuming you're used to the abbreviated way in which C and UNIX assigns words, it duplicates strings :-)
Keeping in mind it's actually not part of the ISO C standard itself(a) (it's a POSIX thing), it's effectively doing the same as the following code:
In other words:
It tries to allocate enough memory to hold the old string (plus a '\0' character to mark the end of the string).
If the allocation failed, it sets
errno
toENOMEM
and returnsNULL
immediately. Setting oferrno
toENOMEM
is somethingmalloc
does in POSIX so we don't need to explicitly do it in ourstrdup
. If you're not POSIX compliant, ISO C doesn't actually mandate the existence ofENOMEM
so I haven't included that here(b).Otherwise the allocation worked so we copy the old string to the new string and return the new address (which the caller is responsible for freeing at some point).
Keep in mind that's the conceptual definition. Any library writer worth their salary may have provided heavily optimised code targeting the particular processor being used.
(a) Keep in mind, however, that functions starting with
str
and a lower case letter are reserved by the standard for future directions. FromC11 7.1.3 Reserved identifiers
:The future directions for
string.h
can be found inC11 7.31.13 String handling <string.h>
:(b) The change would basically be replacing
if (d == NULL) return NULL;
with:It makes a duplicate copy of the string passed in by running a malloc and strcpy of the string passed in. The malloc'ed buffer is returned to the caller, hence the need to run free on the return value.