Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using strdup in C11

Tags:

c

gcc

c11

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?

like image 621
Mike Fisher Avatar asked Oct 28 '13 17:10

Mike Fisher


People also ask

What does strdup () do in C?

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.

Does strdup allocate memory?

The strdup() function allocates sufficient memory for a copy of the string str , does the copy, and returns a pointer to it.

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.

Do you need to malloc before strdup?

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) …


2 Answers

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.

like image 66
Like Avatar answered Oct 01 '22 03:10

Like


you want --std=gnu11 or --std=c11 -D_GNU_SOURCE

like image 42
JTAS Avatar answered Oct 01 '22 03:10

JTAS