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.
6.33 Sebor, Add strnlen to C2X [N 2351]
...
*Straw poll: Should N2351 be put into C2X?
(11/6/6)
Not clear consensus.
As result the function was not added.
One argument against strnlen is that it's a superfluous function, since we already have memchr. Example:
const char str[666] = "hello world";
size_t length1 = strnlen(str,666);
size_t length2 = (char*)memchr(str,'\0',666) - str;
Advantages of memchr:
strnlen in some situations(?).memchr already ought to be in use for the purpose of sanitising supposed string input before calling functions like strcpy, so what purpose strnlen fills is unclear.strnlen which does not tell if it failed or not.Disadvantages:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With