Duplicating Strings with strdup in C
strdup(s) combines malloc(strlen(s) + 1) plus strcpy into one call, returning a fresh heap copy you own and must free. It eliminates the most common dynamic-string bug pattern (wrong size math) by computing the +1 itself — standardized in C23, available via POSIX/string extensions everywhere before that.
Ownership is the whole contract: every strdup needs a matching free, and strndup caps the copy length for untrusted input. Storing command-line args, config values, and parsed fields beyond their source's lifetime is strdup's home turf.
Allocate plus copy
char *d = strdup(s); — heap duplicate, correctly sized including terminator, NULL on allocation failure.
You own it, free it
Every successful strdup transfers ownership to you — free(d) exactly once when done.
strndup bounds it
strndup(s, n) copies at most n characters plus terminator — untrusted input gets capped copies.
Check for NULL
Allocation can fail — NULL-check before use, like every malloc-family call.
#include <stdio.h>#include <stdlib.h>#include <string.h> int main(void) { const char *src = "keep me"; char *copy = strdup(src); if (!copy) return 1; printf("%s\n", copy); free(copy); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.