Functions strdup() and strndup() have finally made it into the upcoming C23 Standard:
7.24.6.4 The
strdupfunctionSynopsis
#include <string.h> char *strdup(const char *s);The
strdupfunction creates a copy of the string pointed to bysin a space allocated as if by a call tomalloc.Returns
Thestrdupfunction returns a pointer to the first character of the duplicate string. The returned pointer can be passed tofree. If no space can be allocated thestrdupfunction returns a null pointer.7.24.6.5 The
strndupfunctionSynopsis
#include <string.h> char *strndup(const char *s, size_t size);The
strndupfunction creates a string initialized with no more thansizeinitial characters of the array pointed to bysand up to the first null character, whichever comes first, in a space allocated as if by a call tomalloc. If the array pointed to bysdoes not contain a null within the firstsizecharacters, a null is appended to the copy of the array.Returns
Thestrndupfunction returns a pointer to the first character of the created string. The returned pointer can be passed tofree. If no space can be allocated thestrndupfunction 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.