Deep Dive: Memory Corruption and Cache Pollution in C++ with Static Lambdas
This article analyzes the bizarre phenomenon in C++ development where unordered_map::find returns an object with mismatched fields after a hit. The root cause lies in defining a static lambda within the function and using reference capture to capture local variables, leading to a dangling reference after the first call, triggering undefined behavior (UB) and polluting cache data in subsequent calls. It is recommended to address this issue by explicitly passing parameters instead of implicit capture, managing lifecycles properly, and utilizing Sanitizer tools.