在 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))?