Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strdup or _strdup?

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.

like image 464
Amir Saniyan Avatar asked Sep 28 '11 11:09

Amir Saniyan


People also ask

Is strdup deprecated?

warning C4996: 'strdup': The POSIX name for this item is deprecated.

Is strdup a standard?

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.

Can strdup fail?

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 .

What is the strdup function?

The function strdup() is used to duplicate a string. It returns a pointer to null-terminated byte string.


2 Answers

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

  • Function names that begin with str and a lowercase letter

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.

like image 182
jpalecek Avatar answered Sep 24 '22 11:09

jpalecek


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.

like image 33
Cheers and hth. - Alf Avatar answered Sep 22 '22 11:09

Cheers and hth. - Alf