Unclear Segmentation fault of using Boost Coroutine(1.55)?

446 Views Asked by At

I write a piece of code which will get a Segmentation fault. I am not sure whether it is a bug of Boost Coroutine or my code below:

#include <string>
#include <functional>
#include <vector>
#include <fstream>
#include <boost/coroutine/coroutine.hpp>
using namespace std;

template <class T>
using C = boost::coroutines::coroutine<T()>;

string foo(C<string>::caller_type & yield,
           std::string fn, int cnt) {
  std::ifstream f(fn);
  // f.close();
  int local_cnt = 0;
  while(local_cnt < cnt) {
      string l;
      getline(f, l);
      local_cnt ++;
      yield(l);
  }
  f.close();
}

int main(int argc, char *argv[])
{
  vector<C<string> > result;
  for(int i = 0; i < 8192; ++i) {
    C<string> obj(bind(foo, std::placeholders::_1, "test.txt", 3)); // line I
    result.push_back(std::move(obj)); // line J
  }
  return 0;
}

test.txt is very large so it will never get the eof before segfault occurring. I use 1.55 of Boost and there are some observation:

  1. seg-error occured in line I
  2. If I delete or move f.close() before yield clause, seg-error disappeared.
  3. If I delete line J in the code, seg-error disappeared.
  4. If I use a smaller number in stead of 8192(say 512), seg-error disappeared.

What's the problem here?

1

There are 1 best solutions below

0
On

"Too many open files" - you exceed the max number of open file descriptors

If I use a smaller number in stead of 8192(say 512), seg-error disappeared.

the seg fault will happen inside the ifstream (does not throw) check ulimit -n cat /proc/sys/fs/file-max sysctl