Page 143 of the K&R book implements a function that makes a copy of a string s:
// Make a duplicate of s
char *strdup(char *s)
{
char *p;
p = (char *) malloc(strlen(s) + 1); // +1 for '\0'
if (p != NULL)
strcpy(p, s);
return p;
}
Is that best practice? That is, don't use strcpy
directly; instead, do a malloc
and then do a strcpy
into the newly malloc
'ed space.
What is the danger of using strcpy
directly?