The strdup() function creates a heap-allocated duplicate of a C-string. It handles malloc and copying in one call so you get an independent string you can modify and later release with free().
01
Duplicate
New heap copy.
02
malloc
Auto alloc.
03
free()
You release.
04
NULL
On failure.
05
POSIX
Not ISO C.
06
vs strcpy
You pick buf.
Fundamentals
Definition and Usage
strdup stands for string duplicate. It computes strlen(s) + 1, allocates that many bytes, copies every character including '\0', and returns the new pointer. The source string can be a literal, a stack buffer, or any valid C-string.
Because memory comes from the heap, the duplicate outlives local arrays when you store the pointer elsewhere. That convenience comes with responsibility: every successful strdup needs a matching free.
💡
Beginner Tip
strdup is POSIX—not guaranteed in strict ISO C. On Linux and macOS it lives in <string.h>. On Windows with MSVC, use _strdup(). When portability matters, wrap it or use malloc(strlen(s)+1) plus strcpy.
Foundation
📝 Syntax
POSIX declaration:
C
char *strdup(const char *s);
Headers
POSIX (Linux, macOS) — #include <string.h>
Free memory — #include <stdlib.h> for free()
Windows (MSVC) — #include <string.h> and _strdup(s)
Parameter
s — null-terminated string to duplicate.
Return Value
Pointer to the newly allocated copy on success.
NULL if allocation fails.
Cheat Sheet
⚡ Quick Reference
Operation
Code
Notes
Duplicate
copy = strdup(s);
Check for NULL
Release
free(copy);
After last use
Bytes allocated
strlen(s) + 1
Includes '\0'
Manual equivalent
malloc + strcpy
Portable fallback
vs strcpy
strdup allocates
strcpy needs your buffer
Duplicate
char *p = strdup(s);
Heap copy
Check
if (p == NULL) { ... }
OOM safe
Free
free(p); p = NULL;
No leak
Windows
_strdup(s)
MSVC name
Hands-On
Examples Gallery
Compile on Linux or macOS with gcc strdup.c -std=c11 -o strdup. Examples use POSIX strdup; see portability notes for Windows.
📚 Getting Started
Duplicate a string, print it, and free the allocated memory.
When malloc fails inside strdup, the function returns NULL. Wrapping the call in a helper keeps main code clean and avoids dereferencing a null pointer.
Example 4 — Portable Manual Duplicate
Implement the same behavior with malloc and strcpy.
This is exactly what typical strdup implementations do internally. Use this pattern on platforms without strdup in the library.
Example 5 — strdup() vs strcpy()
strcpy needs a buffer you size; strdup sizes and allocates for you.
C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
const char *msg = "Same text, different storage";
/* strcpy: you provide the buffer */
char stack_buf[64];
strcpy(stack_buf, msg);
/* strdup: heap buffer allocated for you */
char *heap_copy = strdup(msg);
if (heap_copy != NULL) {
printf("Stack: %s\n", stack_buf);
printf("Heap: %s\n", heap_copy);
free(heap_copy);
}
return 0;
}
📤 Output:
Stack: Same text, different storage
Heap: Same text, different storage
How It Works
Both produce equal C-strings. Stack storage ends when the function returns unless you copy the pointer elsewhere. Heap storage from strdup persists until you free it.
Applications
🚀 Common Use Cases
Save user input — duplicate a line read into a temporary buffer.
Struct ownership — store heap copies of name fields in dynamic records.
API handoff — return a newly allocated string the caller must free.
Config values — copy defaults before parsing modifies them.
Linked lists — attach duplicated string data to nodes.
🧠 How strdup() Works
1
Measure strlen(s)
Compute bytes needed including '\0'.
Size
2
malloc(n)
Return NULL if allocation fails.
Alloc
3
Copy with strcpy/memcpy
Write full string into new buffer.
Copy
=
💾
char* copy
Independent heap string—caller calls free.
Important
📝 Notes
POSIX extension—verify availability or provide a fallback.
Always free() the returned pointer when done.
Do not free the original s unless you allocated it separately.
Passing NULL to strdup is undefined—guard if needed.
Do not mix free with non-malloc allocators unless documented.
Performance
⚡ Optimization
strdup allocates every time. For many duplicates of the same short strings, a string pool or intern table may reduce fragmentation. For occasional copies, strdup is simple and fast enough.
Wrap Up
Conclusion
strdup() duplicates a C-string on the heap in one step. Check for NULL, use the copy freely, and call free() when finished. When strdup is unavailable, use malloc plus strcpy.
Continue with strerror() for system error messages, or review strcpy() for in-buffer copies.
Use for unknown-length strings needing heap lifetime
Provide a manual fallback on embedded toolchains without strdup
❌ Don’t
Leak duplicates by skipping free
Double-free the same pointer
Assume strdup exists on every C compiler
Free the source string thinking it was duplicated in place
Use strdup when a small stack buffer would suffice
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about strdup()
Use these points when duplicating strings in C.
5
Core concepts
💾01
Heap Copy
malloc+dup.
Basics
📝02
free()
Your job.
Memory
🔢03
NULL
OOM check.
Safety
📈04
Independent
Modify copy.
Use case
💬05
vs strcpy
You alloc.
Compare
❓ Frequently Asked Questions
strdup() allocates heap memory large enough for a copy of the source string (including the null terminator), copies the bytes, and returns a pointer to the new string. The original string is not modified.
char* strdup(const char* s); On POSIX systems include <string.h>. You also need <stdlib.h> for free(). Pass a valid null-terminated C-string as s.
You do. Call free() on the pointer returned by strdup() when you no longer need the duplicate. Forgetting to free causes a memory leak.
It returns NULL if malloc fails (out of memory). Always check the result before using or dereferencing the copy.
strdup() is a POSIX function, widely available on Linux and macOS. It is not part of ISO C. Microsoft C provides _strdup() in <string.h>. You can also implement it with malloc and strcpy.
strcpy() copies into a buffer you provide—it does not allocate. strdup() allocates a new buffer on the heap and copies for you. Use strdup when you need an independent copy whose size you do not know ahead of time.
Did you know?
GNU systems also provide strndup(s, n), which duplicates at most n bytes—handy when copying untrusted input with a length cap. It still allocates n+1 or less and must be freed like strdup.