#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");
Can anyone help me explain this?
That's not right.
strdup
returnschar *
already. Something else is wrong. Probably because you did not include the right header file that declares the true return type for this function.man strdup
you will get following things
so
strdup()
returnschar*
there shuld not be any problem Actually in your case it takes implicit declaration ofstrdup()
so by default return type isint
hence you get this warningEither
include<string.h>
or
give forward declaration
char* strdup(const char *);
Also don't forget to
free(s)
in last when all usage are doneYou're missing
#include <string.h>
. In the absence of function signatures, strdup is assumed by the compiler to return an int, hence the warning.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
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: