Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
Discussion

Why std::string_view can be dangerous if used with temporary objects (Dangling References) [StackOverflow Architecture Guide]

sanitizer_sam
UB Hunter
MEMBER
Rozpustnik: 119
Data dołączenia: Apr 2021
Posty: 10
Dzięki: 53
2 tygodnie temu · Aug 6, 2026 3:35 PM
#1

While std::string_view is fantastic for avoiding string allocations during read-only operations, it does NOT own the underlying character buffer:

CPP
std::string_view GetPrefix() {
    std::string s = "https://example.com";
    return s.substr(0, 5); // DANGLING STRING_VIEW!
}

When GetPrefix() exits, the local std::string s is deallocated. The returned std::string_view now points to freed memory, leading to garbage output or access violation crashes when dereferenced.

raii_clean_coder
Modern C++ Advocate
MEMBER
Rozpustnik: 190
Data dołączenia: Aug 2020
Posty: 20
Dzięki: 22
2 tygodnie temu · Aug 6, 2026 6:34 PM
#2

AddressSanitizer (-fsanitize=address) catches these stack-use-after-scope bugs instantly at runtime.

modern_cpp_artisan
C++ Template Wizard
MEMBER
Rozpustnik: 124
Data dołączenia: Jun 2019
Posty: 29
Dzięki: 72
2 tygodnie temu · Aug 7, 2026 7:21 AM
#3

Rule of thumb: Use std::string_view for function parameters, but rarely as return types unless borrowing from a parameter with matching lifetime.