views:

125

answers:

3

Possible Duplicate:
Is there any way a C/C++ program can crash before main()?

Hi, In what scenarios, application crashes before control reaches main() function ? My understanding so far: Global and Global static initialization happen before main(). So if order of initialization is not proper then it could lead crash when using uninitialized pointers etc.

Possible solution: Use functions to get static pointer values, so that they can initialize and return proper pointers.

I read slightly similar thread at http://stackoverflow.com/questions/2814779/program-crashes-in-debugger-before-anything-happens

I am looking for more information. Are there any other scenarios for such crash ? and Whats the solution for avoiding such crashes ?

+3  A: 

Global objects and static class data members have their constructors called before main() is called. If those constructors crash, the program crashes before main() is called. That's one of the many good reasons to avoid globals.

If you are stuck with many globals, you can debug them by putting breakpoints or debug output into their constructors. Dependency issues can be solved by making globals into function-local statics, constructed at first use.

sbi
+1  A: 
  • If you use overly big global members that exhaust the availlable memory, the program will crash or be killed by the OS before main.

  • If your program is linked with a dynamic library that has initialization code, then that code could run before main, depending on your OS. That code could crash.

  • Many other braindead case when it crashes on purpose.

BatchyX
+1  A: 

most of your aswers you already give yourself. But here is some additional info:

in visual c++ you may control the intialization order with:

#pragma init_seg(...)

in gcc its something like this:

__attribute__ ((init_priority (2000)))

You may now read the appropriate docs about details.

kaptnole