Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage of strdup

Tags:

c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{    
    char *s;
    s = strdup("foo");
    printf("%s\n", s);
    getchar();
    return 0;
}

Looks pretty harmless, doesn't it ? But my IDE, which is Dev-C++, gives my the following warning: warning: assignment makes pointer from integer without a cast

The warning disappears if you would change the code like this:

char *s;
s = (char*)strdup("foo");

enter image description here

Can anyone help me explain this?

like image 564
Fihop Avatar asked Nov 16 '12 05:11

Fihop


People also ask

Do I need to free after strdup?

Because also strdup() allocates memory then it must be freed (see doc). strdup is a malloc in disguise. Reading the documentation of a standard function is faster than asking on SO ! strdup is not a Standard C function, however it is in POSIX.

What can I use instead of strdup?

Use g_strdup() instead of strdup().

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.

What is the difference between strdup and Strcpy?

Save this question. Show activity on this post. I read that strcpy is for copying a string, and strdup returns a pointer to a new string to duplicate the string.


1 Answers

You're using Dev-C++, but strdup is not part of the C or C++ standard, it's a POSIX function. You need to define the proper (according to your IDE's documentation) preprocessor symbols in order for strdup to be declared by the header file ... this is necessary in order for the header file not to pollute the name space when included into conforming C or C++ source files.

For a simple portable alternative, consider

char* mystrdup(const char* s)
{
    char* p = malloc(strlen(s)+1);
    if (p) strcpy(p, s);
    return p;
}

Or, if you know strdup is actually in the library, you can copy its declaration from string.h into your own source file or header ... or use the simpler declaration from the man page:

char *strdup(const char *s);
like image 129
Jim Balter Avatar answered Sep 21 '22 22:09

Jim Balter