I tried to log std::exit
calls in my GCC10 compiled Qt 5 application. This fails when turning a QDateTime
object into a string. It can be reproduced with the following snippet:
void exitHandler() noexcept
{
QString b = QDateTime::currentDateTime().toString();
}
int main(int pArgc, char* pArgv[]) noexcept
{
std::atexit(&exitHandler);
QString a = QDateTime::currentDateTime().toString();
std::exit(1);
return 0;
}
Variable a
contains the expected date/time while variable b
is empty. When using UTC time, b
is " GMT". I am not aware of any related restrictions of exit-handlers.
Can someone tell me what is going wrong here?
Exit handlers are called after deinitialization of static variables and thus it is unsafe to call functions that might access static variables.
qdatetime.cpp for instance contains at least one static lookup table for the days of the week which is probably used by toString(). There might be more accesses to (already destroyed) static variables on the call stack.
If you really need this kind of information in the exit handler, you may allocate a static array of chars (without new) and write the date string there from within the main function. I haven't tried but I would expect that memory in the .bss segment is not zeroed on exit and accessing it after global deinitialization is still safe.