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);
A typical implementation strdup(s)does not go stwice as long as an alternative opportunity.
char *d = malloc(strlen(s) +1);
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) {
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, .