K&R 第 6 章中的 strdup() 在未分配 sizeof(char) * strlen(s) 位时如何工作?

Avi*_*yAK 2 c malloc

在 K&R 第 6 章中,它们具有strdup(char *s)用于复制s到内存中并返回其位置的函数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; 
}
Run Code Online (Sandbox Code Playgroud)

但是,在malloc调用中,它们只分配strlen(s) + 1字节。为了使这个字符数组起作用,它不是必须是:malloc(sizeof(char) * (strlen(s) + 1))

ike*_*ami 7

sizeof(char)保证是1,所以

malloc( sizeof(char) * ( strlen(s) + 1 ) )
Run Code Online (Sandbox Code Playgroud)

简化为

malloc( strlen(s) + 1 )
Run Code Online (Sandbox Code Playgroud)

笔记:

  • sizeof 以字节(不是位)为单位返回大小。
  • malloc 需要以字节(而不是位)为单位的大小。
  • 一个字节 ( char) 可能超过 8 位。(金额由 给出CHAR_BIT。)