Hi. I want to share two problems with c++ i encountered and which cause an immediate system crash. In both cases there is no chance to use the debugger - they have to be solved statically.
The problems are related to variables with static memory, like global variables or static class members.
- unhandled exceptions in init phase:
If the variable has a constructor which raises an exception this will happen inside the init phase. As far as i know there is no possibility to handle them and this causes a crash. The system will remain in normal run mode for a second or more and then crash.
An example for this is a false regex:
*.hpp: const std::regex test;
*.cpp: const std::regex test = std::regex(“([a-z]+”);
Here the closing bracket is missing and this will raise the unhandled exception.
- static initialization order fiasco:
This problem is sometimes hard to find and can disappear with some ‘luck’ (see below) . It occurs when the initialization of a variable depends on the instance of another variable defined in another translation unit. This is because the compiler decides the order in which the translation units will be compiled. If one has bad luck then the order is wrong and will cause the problem.
Here a small example (which won’t cause a crash but leads to a false initialization):
*.hpp: const unsigned int test, test2;
a.cpp: const unsigned int test = 2;
b.cpp: const unsigned int test2 = test * 5;
If b.cpp is compiled before a.cpp the value of test2 will be undefined.
When this problem occurs with classes (class initialization depends on another class) the system will crash before the init phase. It wont get to the run mode.
The solution depends on the code. In any case one has to to remove the mutual usage of static memory variables over different translation units.
Here is some information about what to do: Standard C++