C Reference ยท string.h
C strdup() and strndup() functions
Reference for C strdup() and strndup(): copy a string into newly allocated memory, who must free it, availability in C23 and POSIX, and a portable fallback.
strdup() allocates enough memory for a copy of a string with malloc, copies the string including its terminator into it, and returns the new pointer. strndup() does the same for at most n characters and always adds a terminator. You own the result and must release it with free.
Both were POSIX functions for decades and became part of standard C in C23. On many systems they are declared by <string.h> only when you ask for POSIX features.
#define _POSIX_C_SOURCE 200809L #include <string.h> char *strdup(const char *s); char *strndup(const char *s, size_t n);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
char *strdup(const char *s); char *strndup(const char *s, size_t n);
| Name | Description |
|---|---|
s |
The string to copy. |
n |
(strndup) The maximum number of characters to copy, not counting the terminator. |
Returns: a pointer to the new string, or NULL if the allocation failed (and errno is set, typically to ENOMEM).
Errors / undefined behavior: s must be a terminated string (for strndup, terminated or at least n readable bytes). The result must be freed exactly once.
Usage notes
- You must
freethe result. Forgetting it is a memory leak; freeing twice is undefined behavior. It was allocated withmalloc, so usefree, notdeleteor a custom allocator. - Always check for
NULL. Allocation can fail. - Availability.
strdupandstrndupare in C23 and POSIX.1-2008. Under-std=c23with older glibc, define_POSIX_C_SOURCE 200809Lbefore any include, as in the first example, or the compiler may report an implicit declaration. On the runner here, the define is needed. - Older standards and Windows: C11 and earlier do not have them. MSVC provides
_strdup. The fallback shown above is trivial to write. strnduplength: it copies up toncharacters and then terminates, so the result is at mostn + 1bytes. It stops early at a null byte ins.- Storing tokens: a copy decouples your data from a buffer that gets reused or modified, for instance after
strtokor a loop that rereads input withfgets. - Constant-size alternatives: for a fixed buffer use
strcpyorsnprintf, which need no allocation. - Ownership: document who frees. A function that returns a
strdupresult transfers ownership to the caller. See memory ownership patterns.