In C, strdup() allocates a new copy of a C-string on the heap. You own the result, so you must call free() later. It is common on many systems and is not a classic ISO C function.
You pass one C-string. It is required. The result is a new pointer, or NULL when allocation fails. Include <string.h> where strdup is provided.
Syntax
Pass the string to copy. Start with this call.
C
char *copy = strdup("Hello");
Call
What it does
strdup("Hello")
Allocates a new heap string that holds Hello.
Always free the result. On some systems you may need a feature-test macro or a portable malloc + strcpy fallback.
Library declarations
C
char *strdup(const char *s);
Parameters
Parameter
Description
s
Required. The C-string to copy.
Return Value
Return Value
Description
New pointer
A heap copy of the string. You must free it.
NULL
Returned when allocation fails.
C Examples
Example 1 — Basic Duplicate and Free
Create a heap copy, print it, then release the memory.