【发布时间】:2022-01-02 13:04:11
【问题描述】:
我在下面的代码中得到分段文件。 原因在第 10 行,我猜我在哪里使用 char* 缓冲区。 我想知道这是为什么。
是不是因为缓冲区中的内存还没有分配?
代码如下:
1 #include <iostream>
2 #include <fstream>
3
4 int main()
5 {
6 const char* filename = "directory of my file";// mnt/c/Users/...
7 std::fstream fin(filename,std::fstream::in);
8 if(!fin.is_open())
9 std::cout << "Opps!" << std::endl;
10 char* buffer = NULL;//if char buffer[100] then it will be good.
11 while(!fin.eof())
12 {
13 fin.getline(buffer,100);
14 std::cout << buffer << std::endl;
15 }
16 return 0;
17 }
【问题讨论】:
-
根据您的评论,如果您为缓冲区保留 100 个字符,那么将 100 个字符的数据读入这些字符会很好。但是,如果您为缓冲区保留零个字符,那么将数据读入那些(不存在的)字符是一个问题。嗯……
-
与
getline问题无关,但仍与显示的代码相关:Why is iostream::eof inside a loop condition (i.e.while (!stream.eof())) considered wrong?
标签: c++ segmentation-fault getline