Jarry Jarry - 1 year ago 181
C Question

When is it a good idea to use strdup (vs malloc / strcpy)

Can I use

to replace it?
Which one is better?


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


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

Answer Source

strdup(s); does not create a problem when allocation failures, unlike

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

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

// One pass to find length of `s`
char *d = malloc(strlen(s) +1);
// Weak compiler may run 2nd pass to find length of `s`

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

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 its available. Sample implementation:

char *strdup(const char *s) {
  if (s == NULL) return NULL;  // Optional, s should be a string
  size_t siz = strlen(s) + 1;
  char *y = malloc(siz);
  if (y != NULL) {
    memcpy(y, s, siz);
  return y;

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download