什么时候使用strdup是个好主意(vs malloc/strcpy)

Jar*_*rry 4 c

我可以使用mallocstrcpy替换它吗?哪一个更好?

例如:

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)

chu*_*ica 7

哪一个更好?

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库中.

  • 该标准本身没有提到`strdup()`.它只是在§7.31.13中定义了未来的库方向.字符串处理`<string.h>`_Function名称以`str`,`mem`或`wcs`开头,小写字母可以添加到` <string.h>`header._ - 一个一揽子处方,当然包括`strdup()`但不会将所有其他函数名称与`str [az].*`匹配. (2认同)