C中的gets()函数会自动在输入字符串的末尾添加一个NULL字符吗?

Does the gets() function in C automatically add a NULL character at the end of the input string?

我正在编写一个简单的程序来将数字(+ve,32 位)从二进制转换为十进制。这是我的代码:

int main()
{
    int n=0,i=0;
    char binary[33];
    gets(binary);
    for (i = 0; i < 33, binary[i] != '[=10=]'; i++)
        n=n*2+binary[i]-'0';
    printf("%d",n);
}

如果我删除 binary[i]!='[=11=]',那么由于垃圾值,它会给出错误的答案,但如果我不删除,它会给出正确的答案。我的问题是:gets 函数会自动在字符串末尾添加一个 '\0' (NULL) 字符还是这只是巧合?

是的,如果需要,写到 binary[33] 的末尾。

从不使用gets;自动缓冲区溢出。

详情见Why is the gets function so dangerous that it should not be used?

gets 最后一次被 C 标准支持(尽管被弃用)时,它有以下描述(§ 7.19.7.7,gets 函数):

The gets function reads characters from the input stream pointed to by stdin, into the array pointed to by s, until end-of-file is encountered or a new-line character is read. Any new-line character is discarded, and a null character is written immediately after the last character read into the array.

这意味着如果从 stdin 读取的字符串与 s 指向的数组一样长或更长,gets 仍然(尝试)将空字符附加到字符串的末尾。

即使您使用的是支持 gets 的编译器或 C 标准修订版,也不要使用它。 fgets 更安全,因为它需要将缓冲区的大小作为参数写入,并且不会写入超过其末尾。另一个区别是它会将换行符留在缓冲区中,这与 gets 不同。