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

示例

将字符串复制到malloced缓冲区时,请始终记住将加上1 strlen。

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 */