GNU手册 https://www.gnu.org/software/libc/manual/html_node/Line-Input.html
这段话来自 GNU 手册
警告:如果输入数据有空字符,您将无法辨别。所以
除非您知道数据不能包含空值,否则不要使用 fgets。不
使用它来读取用户编辑的文件,因为如果用户插入
空字符,您应该正确处理它或打印一个清晰的
错误信息。我们建议使用 getline 而不是 fgets。
正如我通常所做的那样,我在提问之前会花时间搜索,我确实在五年前的 Stack Overflow 上发现了一个类似的问题:为什么 fgets 函数被弃用? https://stackoverflow.com/questions/16323185/why-is-the-fgets-function-deprecated
尽管 GNU 推荐getline
over fgets
,我注意到getline
in stdio.h
采取任何尺寸的线。它调用realloc
如所须。如果我尝试将大小设置为 10 个字符:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *buffer;
size_t bufsize = 10;
size_t characters;
buffer = (char *)malloc(bufsize * sizeof(char));
if( buffer == NULL)
{
perror("Unable to allocate buffer");
exit(1);
}
printf("Type something: ");
characters = getline(&buffer,&bufsize,stdin);
printf("%zu characters were read.\n",characters);
printf("You typed: '%s'\n",buffer);
return(0);
}
在上面的代码中,输入任意大小的字符串(超过 10 个字符),getline 将读取它并给出正确的输出。
甚至没有必要malloc
,就像我在上面的代码中所做的那样 -getline
为你做。我将缓冲区大小设置为 0,并且getline
will malloc
and realloc
根据需要为我服务。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *buffer;
size_t bufsize = 0;
size_t characters;
printf("Type something: ");
characters = getline(&buffer,&bufsize,stdin);
printf("%zu characters were read.\n",characters);
printf("You typed: '%s'\n",buffer);
return(0);
}
如果运行此代码,您可以再次输入任何大小的字符串,并且它可以工作。即使我将缓冲区大小设置为 0。
我一直在研究 CERT 指南中的安全编码实践www.securecoding.cert.org http://www.securecoding.cert.org
我正在考虑从fgets
to getline
,但我遇到的问题是我无法弄清楚如何限制输入getline
。我认为恶意攻击者可以使用循环发送无限量的数据,并耗尽堆中所有可用的内存?
有没有办法限制输入大小getline
使用或做getline
函数内有一些限制吗?