The Short Test Kept a Dead Cache
I will start with the conclusion, not the tool. Caching c_str across growth is a lifetime bug. A short unit test can still pass cleanly. Later growth is what kills the cached pointer. Did your suite ever cross the capacity line? If it did not, the cache only looked stable. A faster coding model does not relax object lifetime. The language rules did not get softer this year. That gap is why this…
The test case demonstrates a bug where a cached pointer becomes stale after a certain length of input. The issue arises from the `NameTag` struct, which stores a string and a cached pointer to its content. Every time the string is reset or a suffix is added, the cached pointer is updated to point to the new content. However, if the string grows beyond a certain point, the cached pointer becomes invalid, leading to a heap use after free error.
The key takeaway is that even short unit tests can hide subtle bugs if they don't test for capacity limits. The code provided showcases a simple scenario where a small label type stores one string and one raw pointer. Every reset operation writes both the bytes and the cached pointer, while every suffix mutation mutates the string and leaves the pointer unchanged. The test case shows that even a short name can look harmless during review, but a longer export name can still cause issues after an additional append.
To fix this issue, it is essential to freeze the failing length and measure the point at which the c_str address starts moving. By logging relevant fields like size, capacities, and pointer equality, developers can identify the exact moment when the stale pointer becomes a problem. Building a sanitizer binary with AddressSanitizer turned on helps catch the bad read and provides valuable insights into the failing function and the exact address involved.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.