C strcpy() - evil?

前端 未结 17 1307
梦毁少年i
梦毁少年i 2020-12-23 10:50

Some people seem to think that C\'s strcpy() function is bad or evil. While I admit that it\'s usually better to use strncpy() in order to avoid bu

17条回答
  •  醉梦人生
    2020-12-23 10:56

    This answer uses size_t and memcpy() for a fast and simple strdup().

    Best to use type size_t as that is the type returned from strlen() and used by malloc() and memcpy(). int is not the proper type for these operations.

    memcpy() is rarely slower than strcpy() or strncpy() and often significantly faster.

    // Assumption: `s1` points to a C string.
    char *strdup(const char *s1) {
      size_t size = strlen(s1) + 1;
      char *s2 = malloc(size);
      if(s2 != NULL) {
        memcpy(s2, s1, size);
      }
      return s2;
    } 
    

    §7.1.1 1 "A string is a contiguous sequence of characters terminated by and including the first null character. ..."

提交回复
热议问题