When is it recommended to use strdup (vs malloc / strcpy)

Is it possible to use mallocand strcpyto replace it? Which one is better?

eg:.

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);
+4
source share
4 answers

Which one is better?

strdup(s);By itself, it does not cause problems when distribution failures (the call code still needs to be processed a NULLreturn), unlike lower than undefined behavior or UB.

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

A typical implementation strdup(s)does not go stwice as long as an alternative opportunity.

// 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)one will do one run and will use the optimal copy code if it requires it. Perhaps using memcpy()or equivalent.

, , 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;
}

strdup() @Jonathan Leffler @Joshua

malloc()/memcpy()/strcpy() , C. strdup() C, .

+5

, , strdup . strdup == malloc + strcpy

+1

strdup(), libc. strdup() , libc .

libc str...() C, , , - , , ,

. , libc , , , , C libc. , , libc ..

, 0 NULL, '\0'. C , NULL . '\0', , , . '\0' .

+1

strdup() -. malloc() + memcpy() , . , , . , . ,

 typedef struct string
 {
    char* st;
    long buf;
    long n;
 } String;

- , , strdup() , :

 char * stringdup(String *st)
{
    char *res=malloc(st->n);
    res?memcpy(res,st->st,st->n):NULL;
} 

-: , char *, . , , , . char *, . , , . , . , , . , .

UPDATE:

. malloc() + memcpy(), . strdup() strcpy() . , .

+1
source

Source: https://habr.com/ru/post/1655782/


All Articles