Search code examples
ckernighan-and-ritchie

Why have they used function strdup in K&R section 6.5?


In The C Programming Language by KNR - 2nd edition, section 6.5 they have defined a function strdup thus:

char *strdup(char *s)
{
   char *p;

   p = (char *) malloc(strlen(s) + 1) /* +1 for the '\0' */
   if (p != NULL)
     strcpy(p, s);
   return p;
}

The usage is to copy a string onto a member of a structure tnode defined thus:

struct tnode {
char *word;
int count;
struct tnode *left;
struct tnode *right;
};

Called like this:

struct tnode *addtree(struct tnode *p, char *w)
{
...
p->word = strdup(w);
...
}

Why cannot we instead use something like this?

strcpy(p->word, w);

Solution

  • If to use "something like"

    strcpy(p->word, w);
    

    then the program will have undefined behaviour because 1) p->word was not initialized and have any unspecified value; and 2) this statement is trying to write to a memory that was not allocated.

    If you will allocate memory and initialize p->word with the valid address of the memory and then use "something like"

    strcpy(p->word, w);
    

    then in fact you will write the same realization of strdup yourself.