https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109470
Jakub Jelinek <jakub at gcc dot gnu.org> changed: What |Removed |Added ---------------------------------------------------------------------------- CC| |jakub at gcc dot gnu.org --- Comment #7 from Jakub Jelinek <jakub at gcc dot gnu.org> --- You can use -fsanitize=address to get such bugs diagnosed at runtime: g++ -fsanitize=address -o /tmp/pr109470{,.C} -g; /tmp/pr109470 ================================================================= ==2466554==ERROR: AddressSanitizer: stack-use-after-scope on address 0x7ffe08313d80 at pc 0x000000401304 bp 0x7ffe08313d20 sp 0x7ffe08313d18 READ of size 4 at 0x7ffe08313d80 thread T0 #0 0x401303 in main /tmp/pr109470.C:17 #1 0x7f5b06f7958f in __libc_start_call_main (/lib64/libc.so.6+0x2958f) #2 0x7f5b06f79648 in __libc_start_main@GLIBC_2.2.5 (/lib64/libc.so.6+0x29648) #3 0x4010e4 in _start (/tmp/pr109470+0x4010e4) Address 0x7ffe08313d80 is located in stack of thread T0 at offset 64 in frame #0 0x4011b5 in main /tmp/pr109470.C:12 This frame has 2 object(s): [48, 52) 'MAX' (line 14) [64, 68) '<unknown>' <== Memory access at offset 64 is inside this variable HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork (longjmp and C++ exceptions *are* supported) SUMMARY: AddressSanitizer: stack-use-after-scope /tmp/pr109470.C:17 in main Shadow bytes around the buggy address: 0x10004105a760: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x10004105a770: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x10004105a780: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x10004105a790: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x10004105a7a0: 00 00 00 00 00 00 00 00 f1 f1 f1 f1 f1 f1 04 f2 =>0x10004105a7b0:[f8]f3 f3 f3 00 00 00 00 00 00 00 00 00 00 00 00 0x10004105a7c0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x10004105a7d0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x10004105a7e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x10004105a7f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x10004105a800: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 Shadow byte legend (one shadow byte represents 8 application bytes): Addressable: 00 Partially addressable: 01 02 03 04 05 06 07 Heap left redzone: fa Freed heap region: fd Stack left redzone: f1 Stack mid redzone: f2 Stack right redzone: f3 Stack after return: f5 Stack use after scope: f8 Global redzone: f9 Global init order: f6 Poisoned by user: f7 Container overflow: fc Array cookie: ac Intra object redzone: bb ASan internal: fe Left alloca redzone: ca Right alloca redzone: cb ==2466554==ABORTING C++ has always behaved like this and changing it would significantly penalize all the code in the wild that uses C++ correctly. There are some exceptions where the lifetime is extended, but is certainly not one of them.