gpt4 book ai didi

c - getline() 与 fgets() : Control memory allocation

转载 作者:太空狗 更新时间:2023-10-29 16:28:37 25 4
gpt4 key购买 nike

要从文件中读取行,有 getline()fgets() POSIX 函数(忽略可怕的 gets()) .常识认为 getline() 优于 fgets(),因为它根据需要分配行缓冲区。

我的问题是:这不是很危险吗?如果有人意外或恶意创建了一个 100GB 的文件,其中没有 '\n' 字节怎么办 – 这不会让我的 getline() 调用分配一个疯狂的数量吗内存?

最佳答案

My question is: Isn’t that dangerous? What if by accident or malicious intent someone creates a 100GB file with no '\n' byte in it – won’t that make my getline() call allocate an insane amount of memory?

是的,您所描述的是一个似是而非的风险。然而,

  • 如果程序需要一次将整行加载到内存中,那么允许 getline() 尝试这样做本质上并不比使用 编写自己的代码来执行此操作更具风险fgets();和
  • 如果您的程序存在此类漏洞,则可以通过使用 setrlimit() 限制它可以保留的(虚拟)内存总量来降低风险。这可用于导致它失败,而不是成功分配足够的内存来干扰系统的其余部分。

我认为,总体而言,最好的方法是首先编写不需要以整行为单位(一次全部)输入的代码,但这种方法有其自身的复杂性。

关于c - getline() 与 fgets() : Control memory allocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55970169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com