Why does logging in destructor lead to segmentation fault?
Bradley Chatha
sealabjaster at gmail.com
Mon Sep 11 18:08:45 UTC 2023
On Monday, 11 September 2023 at 17:31:17 UTC, Vladimir Marchevsky
wrote:
> https://run.dlang.io/is/NMMpLn - minimal example. Debugging on
> Windows, it crashes on `synchronized(mutex)` with "Access
> violation" trying to read at zero address.
Generally you shouldn't access anything to do with the GC (or
even really global state, such as the `sharedLogger`) within a
dtor.
What's happening is that the GC is running the dtors for all
objects after the main function's finished in a final cleanup,
which prevents you from allocating any GC memory without crashing.
Potentially as well the GC has already cleaned up the
`sharedLogger` causing the null read.
If you look at this example: https://run.dlang.io/is/PvyfOc
By making the class instance `scope` the class is allocated on
the stack, and dtor-ed immediately after the function ends,
rather than when DRuntime is finalising, which prevents the crash
from occurring.
It's a bit of an annoying, weird quirk.
More information about the Digitalmars-d
mailing list