A short C++ program appears to check whether a username matches a privileged account. Its `Sanitize` function accepts a `const std::string&` and returns a `std::string_view` referring to that string’s contents. In the example, the function is called with a string literal, which is implicitly converted into a temporary `std::string`. The function returns a view into that temporary, but the temporary is destroyed at the end of the statement. The `username` view therefore points to an object whose lifetime has ended, and comparing it with the administrator ID accesses invalid memory.
That dangling view causes undefined behavior, so the program’s result is not reliable: with no optimization, Clang and GCC print `false`, while with `-O2` both can print `true`, apparently granting the ordinary username root permissions. The result is also reported under C++17, C++20, and C++23; it is not evidence of a compiler defect or anything supernatural. The behavior depends on details such as the strings having the same length and the input being passed inline, and can disappear after small changes or refactoring. The example’s practical lesson is to avoid returning views that outlive the strings they reference; safer ownership and clearer code can prevent this class of bug.
Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.