When I use strdup
in Microsoft Visual C++, it warns me:
warning C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup. See online help for details.
Thus it seems _strdup
is correct.
But when I use _strdup
in GCC (Fedora Linux OS), the compiler shows an error:
error: ‘_strdup’ was not declared in this scope
With GCC and Linux, compiler does not show any error for strdup
.
Which is correct - strdup
or _strdup
?
Note: I include <string.h>
in my code.
warning C4996: 'strdup': The POSIX name for this item is deprecated.
Most C programmers are familiar with the strdup function. Many of them will take it for granted, yet it is not part of the C Standard (neither C89, C99 nor C11). It is part of POSIX and may not be available on all environments. Indeed Microsoft insisted on renaming it _strdup , adding to confusion.
The chance of strdup failing is determined by the chance of malloc failing. On modern operating systems with virtual memory, a malloc failure is a very rare thing. The OS may have even killed your entire process before the system gets so low on memory that malloc has to return NULL .
The function strdup() is used to duplicate a string. It returns a pointer to null-terminated byte string.
Which is correct?
strdup
is a perfectly correct POSIX function. Nevertheless, it doesn't belong to the standard, and the ANSI C standard reserves some (broad) classes of function names for further use. Among these, there are
therefore, the MS guys decided to replace strdup
with _strdup
.
I'd just continue using strdup
. It's unlikely the C committee will define strdup
to something else than POSIX. Either #define strdup _strdup
or silence the warning.
BTW I hope you see this applies to your functions with names like string_list
etc., too.
strdup
is not a standard C++ function. but it is apparently a Posix function, and anyway it's a well known function which has been there since K&R C. so if you absolutely must use it, do not fret about any possible name collision, and just write strdup
for maximum portability.
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