#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?
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.
Use g_strdup() instead of strdup().
The strdup() function allocates sufficient memory for a copy of the string str , does the copy, and returns a pointer to it.
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.
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);
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