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
