What is the purpose of the strdup() function in C?
What is the purpose of the strdup() function in C?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 current (C17) 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
errnotoENOMEMand returnsNULLimmediately. Setting oferrnotoENOMEMis somethingmallocdoes 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 ofENOMEMso I haven’t included that here(b).Otherwise the allocation worked so we copy the old string to the new string(c) 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.
One other thing to keep in mind, it looks like this is currently slated to be in the C2x iteration of the standard, along with
strndup, as per draftN2912of the document.(a) However, functions starting with
strand a lower case letter are reserved by the standard for future directions. FromC11 7.1.3 Reserved identifiers:The future directions for
string.hcan be found inC11 7.31.13 String handling <string.h>:So you should probably call it something else if you want to be safe.
(b) The change would basically be replacing
if (d == NULL) return NULL;with:(c) Note that I use
strcpyfor that since that clearly shows the intent. In some implementations, it may be faster (since you already know the length) to usememcpy, as they may allow for transferring the data in larger chunks, or in parallel. Or it may not 🙂 Optimisation mantra #1: "measure, don’t guess".In any case, should you decide to go that route, you would do something like: