Functions strdup()
and strndup()
have finally made it into the upcoming C23 Standard:
7.24.6.4 The
strdup
functionSynopsis
#include <string.h> char *strdup(const char *s);
The
strdup
function creates a copy of the string pointed to bys
in a space allocated as if by a call tomalloc
.Returns
Thestrdup
function returns a pointer to the first character of the duplicate string. The returned pointer can be passed tofree
. If no space can be allocated thestrdup
function returns a null pointer.7.24.6.5 The
strndup
functionSynopsis
#include <string.h> char *strndup(const char *s, size_t size);
The
strndup
function creates a string initialized with no more thansize
initial characters of the array pointed to bys
and up to the first null character, whichever comes first, in a space allocated as if by a call tomalloc
. If the array pointed to bys
does not contain a null within the firstsize
characters, a null is appended to the copy of the array.Returns
Thestrndup
function returns a pointer to the first character of the created string. The returned pointer can be passed tofree
. If no space can be allocated thestrndup
function returns a null pointer.
Why was the POSIX-2008 function strnlen
not considered for inclusion?
#include <string.h>
size_t strnlen(const char *s, size_t maxlen);
The strnlen()
function shall compute the smaller of the number of bytes in the array to which s
points, not including the terminating NUL character, or the value of the maxlen
argument. The strnlen()
function shall never examine more than maxlen
bytes of the array pointed to by s
.
Interesingly, this function was proposed in https://www9.open-std.org/JTC1/SC22/WG14/www/docs/n2351.htm
It was discussed at the London meeting in 2019. See the agenda: https://www9.open-std.org/JTC1/SC22/WG14/www/docs/n2370.htm
The discussion minutes can be found at https://www9.open-std.org/JTC1/SC22/WG14/www/docs/n2377.pdf. Page 59.
It was rejected due to no consensus.
As result the function was not added.