Spooky C++

nablags 15 points 12 comments October 31, 2026
www.nablag.com · View on Hacker News

Discussion Highlights (6 comments)

stefanos82

With GCC and `-fsanitize=address,undefined` flag(s) I have catched it during runtime. I've got a nice `==31604==ERROR: AddressSanitizer: stack-use-after-scope on address`

quuxplusone

This is why I call string_view a "parameter-only type": it's fine to take as a parameter, but not fine to return or to store as a variable. (For sane definitions of "fine" and "not fine," of course. The blog post demonstrates one way it can go "not fine.") https://quuxplusone.github.io/blog/2018/03/27/string-view-is...

ranger_danger

> For example, this only works because the string foobarbazboo is the same length as admin_id 12 != 8 I don't get it... > As you can guess, this is an example of undefined behavior causing unintuitive results. No I couldn't... and what undefined behavior where? They don't explain anything.

dingaling911

Oh this is nasty. But the proposed solution of making admin_id a singleton is weird. The real fix is don't pass in a temporary to the sanitize function.

blastonico

std::string_view username = Sanitize("foobarbazboo"); ^- temporary std::string created here std::string_view Sanitize(const std::string& input) { ... } ^ ^- reference to that temporary string +- returns a view to a temporary string std::string_view username = // possibly data freed and dangling string

MathMonkeyMan

You returned a pointer to a temporary. It's nasty but easy to spot. Would you return `input.c_str()`? You might think twice about that, but it's the same thing. My favorite fix is to take a `std::string_view` as the parameter. string_view remove_leading_spaces(string_view input) { auto new_start = find_if(input.begin(), input.end(), [](char ch) { return ch != ' '; }); return string_view(new_start, input.end()); } The result of the undefined behavior in your program is surprising, though. As it usually is.

Semantic search powered by Rivestack pgvector
11,194 stories · 105,736 chunks indexed