我可以使用malloc并strcpy替换它吗?哪一个更好?
例如:
char *s = "Global View";
char *d;
d = strdup(s);
free(d);
Run Code Online (Sandbox Code Playgroud)
要么
char *s = "Global View";
char *d = malloc(strlen(s) +1);
strcpy(d,s);
free(d);
Run Code Online (Sandbox Code Playgroud)
哪一个更好?
strdup(s);当分配失败(调用代码本身不会产生问题仍然需要处理一NULL回),不同的是下面这是未定义的行为或UB.
char *d = malloc(strlen(s) +1);
strcpy(d,s); // should not be called if `d == NULL`.
Run Code Online (Sandbox Code Playgroud)
典型的实现strdup(s)不会s像备用的那样走两倍的长度.
// 1st pass to find length of `s`
char *d = malloc(strlen(s) +1);
// Weak compiler/library may run 2nd pass to find length of `s` and then copy
strcpy(d,s);
Run Code Online (Sandbox Code Playgroud)
一个好的strdup(s)将使一次通过并在长度保证时使用最佳复制代码.也许通过使用memcpy()或等效.
关键是strdup()期望经常使用,并且期望实现这种非标准C库函数的库能够以最佳方式执行.可用时使用最好的工具.示例实施:
char *strdup(const char *s) {
if (s == NULL) { // Optional test, s should point to a string
return NULL;
}
size_t siz = strlen(s) + 1;
char *y = malloc(siz);
if (y != NULL) {
memcpy(y, s, siz);
}
return y;
}
Run Code Online (Sandbox Code Playgroud)
滚动你自己strdup()确实与保留的名字空间碰撞@Jonathan Leffler @Joshua
一个重要的优点malloc()/memcpy()/strcpy()是它们是标准的C库函数. strdup()虽然它是非常常见的,但它不在标准C库中.