liveBook · Manning

Strdup

As explained in Modern C, Third Edition

strdup is a C library function that allocates storage and copies a null-terminated string into it.

strdup allocates storage for a null-terminated string and copies the string into that storage. Its source argument must point to a valid, 0-terminated string; otherwise the length scan is erroneous. section 13.1 section 6.1.5

#include <string.h>
char* strdup( char const s[static 1]);
char* strndup(char const s[static 1], size_t n);

Use the declaration to see strdup beside strndup and the static-array parameter notation. section 13.1

An allocation-plus-copy model

char *strdup(char const s[static 1]) { char *ret = malloc(strlen(s) + 1); return ret ? strcpy(ret, s) : nullptr; } The extra byte reserves space for the terminating 0. If allocation fails, the copy is not attempted and a null pointer is returned. section 13.1

Important constraints:

  • Use strdup only with a genuine null-terminated string; applying string functions to a non-string can cause program failure. section 6.1.5
  • Prefer strndup when a bound is known: it does not read beyond the first n bytes and always terminates the returned buffer. section 13.1
  • Check the result for a null pointer before using the allocated copy, because allocation can fail. section 13.1

How Modern C, Third Edition covers it

How deep it goes
Explains the allocation-and-copy mechanics and input constraints, but defers broader storage-management details.
Examples
Uses an as-if implementation that allocates strlen(s)+1 bytes and copies with strcpy.
What it assumes
Assumes familiarity with C pointers, arrays, null termination, strlen, strcpy, and dynamic allocation.
What you can do after
Apply strdup safely by validating termination and checking its allocation result before using the returned pointer.
How it connects
Connects strdup with malloc, strlen, strcpy, strndup, and null-terminated strings.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.