字符串赋值中的 coredump
我想知道当我们尝试执行 getline() 函数从文件中读取一行时可能出现分段错误的场景
例如:
ifstream h("one.txt");
string s;
getline(h,s); //what assignment to 'h' can lead to segmentaion fault here (or)
//is it possible to get the segmentation fault based on the content of the file?
我需要这个的答案
I want to know the scenario where it is possible to get the segmentation fault when we try to do getline() function to read a line from a file
Eg:
ifstream h("one.txt");
string s;
getline(h,s); //what assignment to 'h' can lead to segmentaion fault here (or)
//is it possible to get the segmentation fault based on the content of the file?
I need the answer for this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想如果“one.txt”包含的行长度超过了内存的长度,您可能会得到未定义的行为(可能表现为段错误)。
getline()
读取的字符数受到string
对象的max_size()
的限制,但这可能会很大。I suppose you'd probably get undefined behavior (which might manifest as a seg fault) if "one.txt" contains a line longer than can fit into memory. The number of characters read by
getline()
is constrained by themax_size()
of thestring
object, but that can be pretty big.假设您的代码没有未定义的行为,这几乎是不可能的 - 否则一切皆有可能,包括分段错误。标准 C++ 库被很多人使用。它经过充分测试,并对输入值进行错误检查。
It's hardly possible, assuming your code has no Undefined Behaviour - otherwise everything is possible including segmentation fault. Standard C++ Library is used by many people. It is well tested and does error checking of input values.