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:
- It tries to allocate enough memory to hold the old string (plus a null 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 so we don't need to explicitly do it in ourstrdup
). - 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).
Keep in mind that's the conceptual definition. Any library writer worth their salary should have provided heavily optimised code targeting the particular processor being used.