Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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

e.g.:

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

or

char *s = "Global View";
char *d = malloc(strlen(s) +1);
strcpy(d,s);
free(d);
like image 717
Jarry Avatar asked Jan 05 '23 07:01

Jarry


1 Answers

Which one is better?

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`.

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

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

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

char *my_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
    #endif
    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;
}

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

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() maybe in C2x: Add strdup and strndup to C2X?

like image 171
chux - Reinstate Monica Avatar answered Jan 14 '23 13:01

chux - Reinstate Monica