Learn C
#include "arraysstrings/strdup_strings.h"

Duplicating Strings with strdup in C

#concept

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.

#how it works
1

Allocate plus copy

char *d = strdup(s); — heap duplicate, correctly sized including terminator, NULL on allocation failure.

2

You own it, free it

Every successful strdup transfers ownership to you — free(d) exactly once when done.

3

strndup bounds it

strndup(s, n) copies at most n characters plus terminator — untrusted input gets capped copies.

4

Check for NULL

Allocation can fail — NULL-check before use, like every malloc-family call.

#example
#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;
}
Output
keep me
1strdup measures, allocates, and copies in one call — no manual strlen + 1 arithmetic to get wrong.
2The NULL check guards allocation failure before any use.
3Use, print, free — complete owned-string lifecycle with nothing leaked.
#use cases
Keeping parsed fields and arguments past their source's lifetime
Storing config and CLI strings in long-lived structures
Capped copies of untrusted input with strndup
Replacing hand-rolled malloc+strcpy pairs everywhere

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.