Ray's Knowledge Base
Unlock

Assigning an empty value in a shutdown hook frees nothing on libstdc++

PitfallVerified 5 Nov 2026Holds anywhere
Pitfall. The symptom, what causes it, and the fix that was run and seen to work.

Symptom#

Tests pass all their checks but fail a memory exit check on Linux with GCC. The check reports a few bytes still allocated at exit (48 bytes in 58 tests). The same tests pass on macOS.

Cause#

A shutdown hook "freed" cached strings or paths with value = {} or value = "". libstdc++ keeps the old heap buffer on that assignment. libc++ (macOS, Clang) frees it. So only Linux leaks.

Fix#

Swap the old value into a local that dies at the end of the hook, so its destructor frees the buffer:

T().swap(value);   // or: { T old; old.swap(value); }

Check other places that use the same pattern.

Evidence#

Corona (GCC 12) failed 58 tests on the exit check. After the swap fix, Corona passed 510 of 510 tests with 0 warnings.

Also found by searching

  • 48 bytes still allocated at exit on Linux but not on macOS
  • memory exit check fails only with GCC
  • assigning an empty std::string does not free the buffer
  • how do I free a cached string or path in a shutdown hook