I am able to compile the following using gcc version 4.7.2
#include <string.h>
int main(){
char text[] = "String duplicate";
char* dup = strdup(text);
return 0;
}
But when I used the --std=c11 flag, I get the following warning:
warning: implicit declaration of function ‘strdup’ [-Wimplicit-function-declaration]
warning: initialization makes pointer from integer without a cast [enabled by default]
What changed to cause this warning?
The strdup() and strndup() functions are used to duplicate a string. strdup() : Syntax : char *strdup(const char *s); This function returns a pointer to a null-terminated byte string, which is a duplicate of the string pointed to by s.
The strdup() function allocates sufficient memory for a copy of the string str , does the copy, and returns a pointer to it.
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.
You don't need to do a malloc() yourself; indeed, it immediately leaks if you do it since you overwrite the only pointer to the space you allocated with the pointer to the space that strdup() allocated. Hence: char *variable = strdup(word); if (variable == 0) …
Read the manual of strdup by
man strdup
You can find that
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
strdup(): _SVID_SOURCE || _BSD_SOURCE || _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED || /* Since glibc 2.12: */ _POSIX_C_SOURCE >= 200809L
It denotes that strdup conforms to SVr4, 4.3BSD, POSIX.1-2001.
So you can get rid of the warnings by
gcc -D_BSD_SOURCE -std=c11 <your source file>
I guess the warnings are caused by c11 not enabling one of the above macros.
you want --std=gnu11 or --std=c11 -D_GNU_SOURCE
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