Home > database >  segmentation fault with char* buffer in getline() function
segmentation fault with char* buffer in getline() function

Time:11-24

I get segmentation file in the below code. The reason is in the line 10 I guess where I'm using char* buffer. I want to know why is this.

Is it because the memory in the buffer is not still allocated?

Here is the code:

  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 }

CodePudding user response:

Is it because the memory in the buffer is not still allocated?

Yes. In fact, you don't even have a buffer. The pointer buffer is NULL, meaning it points to a memory location that you have no business accessing. You then went ahead and told getline() it can write up to 100 bytes starting from that address.

It worked when you used char buffer[100] because that's an array allocated on the stack, large enough to hold the upper limit of 100 bytes that you promised getline() could be written.

If you don't know the length of a line in advance and want to be able to handle arbitrary lengths, consider using std::string instead. Here is the typical way to read a file line-by-line in C :

std::string line;
while (std::getline(fin, line))
{
    std::cout << line << "\n";
}

Please also read: Why is iostream::eof inside a loop condition considered wrong?

  • Related