Join Nostr
2025-08-01 21:25:45 UTC
in reply to

Dan Cross on Nostr: it looks like, for this specific case, Address Sanitizer finds an issue pretty ...

it looks like, for this specific case, Address Sanitizer finds an issue pretty quickly.

```
term% cat foo.cc
#include <iostream>
#include <vector>

int
main()
{
std::vector<int> v{0, 1, 2, 3, 4};
for (const auto elem: v)
std::cout << "elem= " << elem << std::endl;
for (auto it = v.cbegin(); it != v.cend(); ++it) {
if (*it % 2)
v.emplace_back(1);
}
for (const auto elem: v)
std::cout << "elem= " << elem << std::endl;
return 0;
}
term% clang++ -std=c++23 -fsanitize=address,undefined -Wall -Wextra -o foo foo.cc
term% ./foo
foo(22239,0x20c2e5f00) malloc: nano zone abandoned due to inability to reserve vm space.
elem= 0
elem= 1
elem= 2
elem= 3
elem= 4
=================================================================
==22239==ERROR: AddressSanitizer: heap-use-after-free on address 0x603000001c98 at pc 0x000102264f94 bp 0x00016db9a650 sp 0x00016db9a648
READ of size 4 at 0x603000001c98 thread T0
#0 0x000102264f90 in main+0x6b0 (foo:arm64+0x100000f90)
[snip]
#9 0x000102266308 in int& std::__1::vector<int, std::__1::allocator<int>>::emplace_back<int>(int&&)+0x224 (foo:arm64+0x100002308)
#10 0x000102265028 in main+0x748 (foo:arm64+0x100001028)
#11 0x00019de36b94 in start+0x17b8 (dyld:arm64e+0xfffffffffff3ab94)

previously allocated by thread T0 here:
[snip]
#8 0x000102266928 in std::__1::vector<int, std::__1::allocator<int>>::vector[abi:ne190102](std::initializer_list<int>)+0x328 (foo:arm64+0x100002928)
#9 0x0001022655a4 in std::__1::vector<int, std::__1::allocator<int>>::vector[abi:ne190102](std::initializer_list<int>)+0x60 (foo:arm64+0x1000015a4)
#10 0x000102264b54 in main+0x274 (foo:arm64+0x100000b54)
#11 0x00019de36b94 in start+0x17b8 (dyld:arm64e+0xfffffffffff3ab94)

SUMMARY: AddressSanitizer: heap-use-after-free (foo:arm64+0x100000f90) in main+0x6b0
[snip]
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
==22239==ABORTING
term% clang++ --version
Apple clang version 17.0.0 (clang-1700.0.13.5)
Target: arm64-apple-darwin24.5.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
term%
```