On cpp reference page for strdup, I notice it says,
As all functions from Dynamic Memory TR, strdup is only guaranteed to be available if
__STDC_ALLOC_LIB__
is defined by the implementation and if the user defines__STDC_WANT_LIB_EXT2__
to the integer constant 1 before including string.h.
I thought that what the function strdup
do is just simply malloc
a space and strcpy
the source to that space, and I also found its implementation in glibc.
char * __strdup (const char *s)
{
size_t len = strlen (s) 1;
void *new = malloc (len);
if (new == NULL)
return NULL;
return (char *) memcpy (new, s, len);
}
There's nothing special in its implementation, so why shall I define __STDC_WANT_LIB_EXT2__
to integer 1 before using strdup
(or any other Dynamic Memory TR)? What does defining __STDC_WANT_LIB_EXT2__
do here?
CodePudding user response:
As the top of the page you linked clarifies, the strdup
function was not officially a part of the C Standard Library until C23, which has not yet been finalized.
Before that, it was available as a "dynamic memory extension", a set of extensions to the C standard introduced in 2010. Compilers and implementations of the C Standard Library (such as the GNU C Standard Library) which implemented these extensions usually "hid" them behind macros,
such as STDC_WANT_LIB_EXT2
in this case. See Feature Test Macros for more Glibc examples of those special feature macros.
strdup
in particular has existed long before 2010. as part of the POSIX standard, which glibc implements, and as such you do not need to explicitly define the aforementioned macros if you are using the GNU toolchain.
See here for more examples of POSIX functions.