问问题
1760 次
2 回答
7
您不能拥有自己的名称以 开头的函数str
。整个“命名空间”在 C 中是保留的。
在这种情况下,strdup()
是来自 的标准函数<string.h>
,您的函数声明与之冲突。
请注意,仅停止使用是不够的<string.h>
,该名称仍被保留,因此您无法有效使用它。
还有一些注意事项:
- 输入没有被写入,所以它应该是一个
const
指针。 - 请不要强制转换
malloc()
in C的返回值。 - 您
strdup()
的工作设备严重损坏,strcmp()
当它意味着它时它会调用strcpy()
。 - 您的使用
sizeof(strlen(s))
是完全错误的,即使您修复了strcmp()
/问题也会导致大量strcpy()
问题。
一个合理的strdup()
实现是:
char * my_strdup(const char *s)
{
char *r = NULL;
if(s != NULL)
{
const size_t size = strlen(s) + 1;
if((r = malloc(size)) != NULL)
memcpy(r, s, size);
}
return r;
}
我使用memcpy()
,因为我知道长度,它可以更快。
于 2014-02-18T10:16:33.603 回答
2
strdup is allready defined in string.h. Just rename your function.
于 2014-02-18T10:14:01.093 回答