Segmentation Fault before main

I've been running into a problem where somehow my code is causing segmentation faults before any of my main actually runs.

Usually, this means that the data structures that your main tries to place in the automatic storage area overflow the stack. In your situation, it looks like the GRAPH is a suitable suspect to do just that: it has a 2D array with 571536 pointers, which could very well overflow the stack before your main gets a chance to start.

One solution to this problem would be moving the GRAPH into the static area: since you allocate it in the main, it's going to be only one instance of it anyway, so declaring it static should fix the problem:

static GRAPH g;

You might also want to allocate it in the dynamic area using malloc, but in this case it probably does not matter.


I had faced "Segmentation fault occurs before main() execution begins" issue in my C++ code. Let me try to explain what my issue was and how I could solve it.

  1. A global/static class instance is present in code.
  2. Its constructor is invoked before main() begins.
  3. Inside constructor,in an error handling part, std::cerr is used to display error.
  4. std:cerr was not initialized when constructor was executed.
  5. Even though it says, if #include iostream is there before object is defined then std::cerr is initialized, it was not. https://en.cppreference.com/w/cpp/io/cerr
  6. If object of std::ios_base::Init is created before constructor, it ensures proper init and deinit of default c++ streams.
  7. why std::cerr was not initialized, In c++11 objects in iostream are init before other global objects. But in c++03, it is unspecified. Use std::ios_base::Init as a private member of class to ensure it is init before stream functions are executed. Is std::cout guaranteed to be initialized?

Your problem is not "before main" as you state, but in the first few lines of your program. You are not initializing fp, so it could go anywhere. You also have memory errors in your loop with new. You need to copy the value into newly allocated memory.

You cannot see the printfs in your code because the output is buffered and your code crashes before the buffer is flushed. If you put exit(0) just after your printf("error");, you'll see that it works.


One possible reason for segmentation fault before main is the program was mistakenly linked with -shared option. I wasted a lot of time trying to debug it.