本文介绍了什么时候使用strdup是一个好主意(vs malloc/strcpy)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 malloc strcpy 替换它吗?哪个更好?

Can I use malloc and strcpy to replace it?Which one is better?

例如:

char *s = "Global View";
char *d;
d = strdup(s);
free(d);

char *s = "Global View";
char *d = malloc(strlen(s) +1);
strcpy(d,s);
free(d);

推荐答案

strdup(s); 本身在分配失败时不会产生问题(调用代码 NULL 返回),与下面的不同>未定义的行为或UB.

strdup(s); itself does not create a problem when allocation failures (calling code still needs to handle a NULL return), unlike the below which is undefined behavior or UB.

char *d = malloc(strlen(s) +1);
strcpy(d,s); // should not be called if `d == NULL`.

strdup(s)的典型实现不会像替代方法那样遍历 s 的长度两次.

A typical implementation of strdup(s) does not walk the length of s twice like the alternate might.

// 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);

好的 strdup(s)将通过一次,并在长度允许时使用最佳复制代码.也许通过使用 memcpy()或等效的方法.

A good strdup(s) will make one pass and use optimal copy code when the length warrants it. Perhaps by using memcpy() or equivalent.

关键是应该经常使用 strdup(),而实现此非标准C库功能的库是预计将被设计为最佳性能.尽可能使用最好的工具.实施示例:

The key is that strdup() is expected to be used often and a library that implements this non-standard C library function is expected to be crafted to perform optimally. Use the best tool when it is available. Sample implementation:

#include <errno.h>
#include <stdlib.h>

char *strdup(const char *s) {
  if (s == NULL) { // Optional test, s should point to a string
    #ifdef EINVAL
      errno = EINVAL;  // For systems that support this "invalid argument" errno
    #ednif
    return NULL;  
  }
  size_t siz = strlen(s) + 1;
  char *y = malloc(siz);
  if (y != NULL) {
    memcpy(y, s, siz);
  } else {
    #ifdef ENOMEM
      errno = ENOMEM;  // For systems that support this "out-of-memory" errno
    #else
      ;
    #endif
  }
  return y;
}

滚动自己的 strdup()确实与保留的名称空间冲突

Rolling your own strdup() does collide with reserved name space @Jonathan Leffler @Joshua

malloc()/memcpy()/strcpy()的一个重要优点是它们是标准的C库函数.尽管非常普遍实现,但 strdup()不在标准C库中.

An important advantage to malloc()/memcpy()/strcpy() is that they are standard C library functions. strdup() is not in the standard C library, although it is very commonly implemented.

[edit] strdup()可能在C2x中:将strdup和strndup添加到C2X ?

[edit] strdup() maybe in C2x: Add strdup and strndup to C2X?

这篇关于什么时候使用strdup是一个好主意(vs malloc/strcpy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 18:48