In C, strndup() allocates a new string containing at most n characters from a source C-string. It stops earlier when it reaches the source terminator and always adds a new '\0' to the copy.
The result belongs to the caller and must be released with free(). strndup() is specified by POSIX rather than classic ISO C, so availability and feature-test requirements depend on the system.
Syntax
Start with this concrete call, then adjust the values for your buffer.
C
char *copy = strndup(source, 5);
Call
What it does
strndup(source, 5)
Allocates a copy of at most the first five source characters.
Include <string.h> for the declaration and <stdlib.h> for free().
Library declaration
C
char *strndup(const char *s, size_t n);
Parameters
Parameter
Description
s
Required. Null-terminated source string to duplicate.
n
Maximum number of source characters to copy, not counting the new terminator.
Return Value
Return Value
Description
New pointer
A heap-allocated, null-terminated copy containing at most n characters.
NULL
Returned when memory allocation fails.
C Examples
Example 1 — Duplicate a String Prefix
Keep only the first five characters of a longer source string.