忘记为 0 分配一个额外的字节

当你将字符串复制到 malloced 缓冲区时,请务必记住向 strlen 添加 1。

char *dest = malloc(strlen(src)); /* WRONG */
char *dest = malloc(strlen(src) + 1); /* RIGHT */

strcpy(dest, src);

这是因为 strlen 在长度上不包括尾随\0。如果你采用 WRONG(如上所示)方法,在调用 strcpy 时,你的程序将调用未定义的行为。

它也适用于从 stdin 或其他来源读取已知最大长度的字符串的情况。例如

#define MAX_INPUT_LEN 42

char buffer[MAX_INPUT_LEN]; /* WRONG */
char buffer[MAX_INPUT_LEN + 1]; /* RIGHT */

scanf("%42s", buffer);  /* Ensure that the buffer is not overflowed */