skip to content

In C++, why can a global object's destructor crash at program exit when it calls a function that returns a function-local static?

level: seniorimportance: should knowfreq 38%

answer

  1. reverse order of construction
  2. who finished constructing first
  3. built during main means destroyed earlier
  4. touch it in the constructor

basics

~20 s

Static objects are destroyed in reverse order of construction. If the function-local static was first built after the global, it is destroyed before the global's destructor runs, so that destructor uses a dead object, which is undefined behaviour.

solid answer

~40 s

During `std::exit`, which returning from `main` invokes, constructed static-duration objects are destroyed in **reverse order of the completion of their construction**, and a function-local static is ordered by when its initialization actually finished. In the plugin host, `PluginHost host;` is constructed before `main`, while `registry()`'s static map is first built inside `main`. So the map is destroyed first, and when `~PluginHost` iterates `registry()`, the standard says control passing through a destroyed block variable's definition is **undefined behaviour**. With AddressSanitizer it was a heap-use-after-free; without it, a segmentation fault. The fix is to make the dependency finish construction first: call `registry()` from `PluginHost`'s constructor, so the map is destroyed after the host. The alternatives are a registry that is deliberately never destroyed, or not using shared statics from destructors at all.

code

cpp · 24 lines
cpp
#include <cstdio>
#include <map>
#include <string>
std::map<std::string, int>& registry() {
  static std::map<std::string, int> instance;
  return instance;
}
struct PluginHost {
  PluginHost() {
#ifdef FIX
    registry();  // construct the registry first, so it is destroyed after us
#endif
    std::puts("PluginHost constructed");
  }
  ~PluginHost() {
    for (const auto& [name, id] : registry())
      std::printf("~PluginHost unloads %s\n", name.c_str());
  }
};
PluginHost host;  // namespace-scope object, constructed before main
int main() {
  registry().emplace("png", 1);  // the registry is first built here, after host
  std::puts("main returns");
}

go deeper

for a junior

Remember that globals and static locals are destroyed when the program exits, in reverse order of construction.

for a middle

Explain that a function-local static joins the destruction order when its initialization completes, so first use late in the program means destruction early.

for a senior

Diagnose a crash after main as an exit-time ordering bug, confirm it with AddressSanitizer, and fix it by ordering construction or by never destroying the shared object.

for a principal

Weigh destroying static objects at all against leaving them alive until the process ends, and set a shutdown policy that releases external resources explicitly.

## The termination rule When `main` returns, it invokes `std::exit`, which does three things in order: 1. Destroys the objects with **thread storage duration** belonging to the calling thread. 2. Destroys the constructed objects with **static storage duration** and calls the functions registered with `std::atexit`. 3. Flushes and closes C streams, then returns control to the host environment. For step 2 the standard sets the order: if the construction of one static object strongly happens before that of another, the second is fully destroyed before the destruction of the first begins. In plain words, **reverse order of the completion of construction**. Two details matter: - A **function-local static** joins this order when its initialization *completes*, which may be long after `main` has started. - A constructor that calls a function which builds a function-local static finishes **after** that static, so the static is destroyed after it. A final paragraph covers exactly this bug: if a destructor of a static object calls a function whose block-scope static has already been destroyed, and control passes through that static's definition, the behaviour is **undefined**. ## How the plugin host fails at exit In the code example, `PluginHost host;` at namespace scope is constructed before `main`. Its constructor does not touch the registry. `main` then calls `registry()` for the first time, so the map is constructed **after** `host`. At exit the order reverses: the map is destroyed first, freeing its nodes, and then `~PluginHost` calls `registry()` and iterates the destroyed map. On Apple clang 21 the plain build died with a segmentation fault (exit status 139) and lost the buffered output. With `-fsanitize=address` the report was a **heap-use-after-free** in `~PluginHost`, because the map's nodes had already been freed. A shorter destructor that only read `registry().size()` printed a plausible count and exited cleanly: undefined behaviour that happened to look fine. That variant is the dangerous one, because it passes tests. ## Fixes 1. **Construct the dependency first.** Call `registry()` in `PluginHost`'s constructor. The map then finishes construction before `host` does, so it is destroyed after `~PluginHost` returns. Built with `-DFIX`, the example unloads `png` cleanly under AddressSanitizer. 2. **Never destroy it.** Allocate the registry once and keep only a pointer: `static auto* instance = new std::map<std::string, int>();` then `return *instance;`. With no exit-time destructor there is nothing to order; the operating system reclaims the memory when the process ends. On Clang, `[[clang::no_destroy]]` on the static does the same without the heap allocation. 3. **Shut down explicitly.** Unload plugins from `main` before it returns, and keep destructors of static objects trivial. This is the most readable order, and it suits a host that must release external resources deterministically. 4. **Skip static destruction.** `std::quick_exit` does not destroy static objects at all. It removes the symptom for a program that must terminate fast, but it also skips every other cleanup. | Fix | Exit-time destructor runs? | Cost | |---|---|---| | construct the dependency first | yes, in a safe order | one extra call in a constructor, easy to forget | | never destroy it | no | memory reclaimed by the operating system, destructor side effects lost | | explicit shutdown from `main` | yes, under your control | the order must be maintained by hand | ## Diagnosing it - A crash **after** the last line of `main` runs points at static destruction; a backtrace that passes through `exit` confirms it (on the macOS build above, `exit` called `__cxa_finalize_ranges`, which called `~PluginHost`). - Clang's `-Wexit-time-destructors` lists every declaration that needs an exit-time destructor, which tells you what takes part in the order. - Building with AddressSanitizer turns the silent variant into a report. ## The point to make The startup order problem has a mirror image at exit. Construct-on-first-use fixes startup, but the lazily built object then joins the destruction order late and dies early. A strong answer states the reverse-order rule, explains why first use inside `main` makes the static die before older globals, and fixes it by ordering construction or by not destroying the shared object.

  • Why does calling registry() in PluginHost's constructor change the destruction order?
    Destruction follows the reverse of the completion of construction. If `PluginHost`'s constructor calls `registry()`, the map's initialization completes inside that constructor, before the constructor itself completes. The map is therefore older, so it is destroyed after `~PluginHost` has returned. The call only has to happen once, before the constructor finishes.
  • What does deliberately never destroying a static cost?
    Its destructor never runs, so anything that destructor would do, such as flushing a file or closing a connection, does not happen at exit. The memory itself is reclaimed by the operating system when the process ends. It suits caches and registries of plain data, not objects that own external resources needing an orderly close.

  • Static objects are destroyed in the order they were constructed.
  • A function-local static is always destroyed after every global object.
  • If the destructor printed the right value, the code has no lifetime bug.
  • Objects with static storage duration are never destroyed, so exit order does not matter.
  • The crash after main is caused by the operating system freeing memory too early.