Developer knowledge network ยท moderated exchange

Komunitas Kode Tidak Dapat Diandalkan

Riset Pengembang, Rekayasa Terbalik & Komunitas Pengkodean

Knowledge indexHidup
4Categories
919Threads
2.8KPostingan
Discussion

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

sanitizer_sam
UB Hunter
MEMBER
Reputasi: 119
Tanggal Bergabung: Apr 2021
Postingan: 10
Terima kasih: 53
2 minggu yang lalu ยท 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
Reputasi: 190
Tanggal Bergabung: Aug 2020
Postingan: 20
Terima kasih: 22
2 minggu yang lalu ยท 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
Reputasi: 124
Tanggal Bergabung: Jun 2019
Postingan: 29
Terima kasih: 72
2 minggu yang lalu ยท 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.