Enable address sanitizer (ASan) stack-use-after-return checking (detect_stack_use_after_return=1
).
Example:
0#include <iostream>
1#include <string>
2
3const std::string& get_string(int i) {
4 return std::to_string(i);
5}
6
7int main() {
8 std::cout << get_string(41) << "\n";
9}
Without address sanitizer (ASan) stack-use-after-return checking:
0$ ./stack-use-after-return
1
2$
With address sanitizer (ASan) stack-use-after-return checking:
0$ ASAN_OPTIONS="detect_stack_use_after_return=1" ./stack-use-after-return
1=================================================================
2==10400==ERROR: AddressSanitizer: stack-use-after-return on address 0x7f7fa0400030 at pc 0x00000049d2cc bp 0x7ffcbd617070 sp 0x7ffcbd616820
3READ of size 2 at 0x7f7abbecd030 thread T0
4 [#0](/bitcoin-bitcoin/0/) 0x439781 in fwrite
5 [#1](/bitcoin-bitcoin/1/) 0x7f7ac0504cb3 in std::basic_ostream<char, std::char_traits<char> >& std::__ostream_insert<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*, long) (/usr/lib/x86_64-linux-gnu/libstdc++.so.6+0x113cb3)
6 [#2](/bitcoin-bitcoin/2/) 0x4f9b5f in main stack-use-after-return.cpp:9:15
7 [#3](/bitcoin-bitcoin/3/) 0x7f7abf440b96 in __libc_start_main
8 [#4](/bitcoin-bitcoin/4/) 0x41bbc9 in _start
9…
10$