0

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 
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Tristan
  • 43
  • 4

1 Answers1

2

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.

bartop
  • 9,971
  • 1
  • 23
  • 54