Search code examples
c++linuxfstreamofstream

Segfault on ofstream::open() if defined outside of function


I'm writing a little shared library to test some things via LD_PRELOAD and I want to write logs to a file.

The following code works:

void ctor() __attribute__((constructor));
void dtor() __attribute__((destructor));

void ctor() {
  std::ofstream log_file;
  log_file.open("/home/tristan/Test.log");
  log_file << "Log Stuff..." << std::endl;
  log_file.close();
}

This causes a Segfault:

void ctor() __attribute__((constructor));
void dtor() __attribute__((destructor));

std::ofstream log_file;

void ctor() {
  log_file.open("/home/tristan/Test.log");
  log_file << "Log Stuff..." << std::endl;
  log_file.close();
}

Why is that? Something to do with the constructor attribute perhaps?

My GCC flags are as follows:

gcc -fPIC -m64 -shared -lstdc++ -o Test.so *.cpp 

Solution

  • This is because of the __attribute__((constructor)). The ctor function is called before global variable std::ofstream log_file is initialized and so causes the segfault.