Manoj Doubts Manoj Doubts - 1 month ago 6
C Question

strdup() - what does it do in C?

What is the purpose of the

strdup()
function in C?

Answer

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 (it's a POSIX thing), it's effectively doing the same as the following code:

char *strdup (const char *s) {
    char *d = malloc (strlen (s) + 1);   // Space for length plus nul
    if (d == NULL) return NULL;          // No memory
    strcpy (d,s);                        // Copy the characters
    return d;                            // Return the new string
}

In other words:

  1. It tries to allocate enough memory to hold the old string (plus a null character to mark the end of the string).
  2. If the allocation failed, it sets errno to ENOMEM and returns NULL immediately (setting of errno to ENOMEM is something malloc does so we don't need to explicitly do it in our strdup).
  3. 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.

If you're part of the crowd that abhors multiple exit points in functions (I don't unless it affects readability, which I don't believe to be the case for such a short function), you can write the code as:

char *strdup (const char *s) {
    char *d = malloc (strlen (s) + 1);   // Allocate memory
    if (d != NULL) strcpy (d,s);         // Copy string if okay
    return d;                            // Return new memory
}