How does strdup() in K&R chapter 6 work when it doesn't assign sizeof(char) * strlen(s) bits?

Viewed 46

In K&R Chapter 6 they have the function strdup(char *s) which is meant to copy s into memory and return its location, p.

/* strdup: make a duplicate of s */ 
char *strdup(char *s) {
    char *p; 

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

However, in the malloc call, they only assign strlen(s) + 1 bytes. In order for this array of chars to work, wouldn't it have to be: malloc(sizeof(char) * (strlen(s) + 1))?

1 Answers

sizeof(char) is guaranteed to be 1, so

malloc( sizeof(char) * ( strlen(s) + 1 ) )

simplifies to

malloc( strlen(s) + 1 )

Note:

  • sizeof returns a size in bytes (not bits).
  • malloc requires a size in bytes (not bits).
  • A byte (char) may have more than 8 bits. (The amount is given by CHAR_BIT.)
Related