←back to thread

237 points ekr____ | 1 comments | | HN request time: 0s | source
Show context
AdieuToLogic ◴[] No.42733902[source]
The example strdup implementation:

  char *strdup(const char *str) { 
    size_t len = strlen(str);
    char *retval = malloc(len);
    if (!retval) {
      return NULL; 
    }
    strcpy(retval, str);
    return retval;
  }
Has a very common defect. The malloc call does not reserve enough space for the NUL byte required for successful use of strcpy, thus introducing heap corruption.

Also, assuming a NULL pointer is bitwise equal to 0 is not portable.

replies(2): >>42734401 #>>42750665 #
1. ekr____ ◴[] No.42750665[source]
Aargh. You're totally right about the off by one error. Thanks for catching it.

I don't believe you're right about the comparison to zero, however, as the comment below indicates.