usage of strdup

2020-07-14 12:43发布

#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?

标签: c
4条回答
家丑人穷心不美
2楼-- · 2020-07-14 13:04

That's not right. strdup returns char * already. Something else is wrong. Probably because you did not include the right header file that declares the true return type for this function.

#include <string.h>
查看更多
女痞
3楼-- · 2020-07-14 13:08

man strdup

you will get following things

#include<string.h>

char* strdup(const char * s);

so strdup() returns char* there shuld not be any problem Actually in your case it takes implicit declaration of strdup() so by default return type is int hence you get this warning

Either include<string.h>

or

give forward declaration char* strdup(const char *);

Also don't forget to free(s) in last when all usage are done

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-07-14 13:09

You're missing #include <string.h>. In the absence of function signatures, strdup is assumed by the compiler to return an int, hence the warning.

查看更多
闹够了就滚
5楼-- · 2020-07-14 13:17

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);
查看更多
登录 后发表回答