[LifetimeSafety] Diagnose incorrect usage of `unique_ptr` / `shared_ptr` raw pointer constructor
- Dominant language
- LLVM
- Stars
- 40.5k
- Forks
- 18.7k
- PR merge metrics
- PR metrics pending
Description
https://godbolt.org/z/eh43s5qEM
`-Werror=lifetime-safety -std=c++20 -fsanitize=address`
```cpp
#include
auto f1() {
std::unique_ptr p;
{
int a = 42;
p = std::unique_ptr{&a};
}
}
```
```
=================================================================
==1==ERROR: AddressSanitizer: attempting free on address which was not malloc()-ed: 0x7183ae5f0040 in thread T0
#0 0x567f2d76f712 in operator delete(void*, unsigned long) /root/llvm-project/compiler-rt/lib/asan/asan_new_delete.cpp:190:3
#1 0x567f2d7707bb in std::default_delete::operator()(int*) const /opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/16.0.1/../../../../include/c++/16.0.1/bits/unique_ptr.h:92:2
#2 0x567f2d7703af in std::unique_ptr>::~unique_ptr() /opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/16.0.1/../../../../include/c++/16.0.1/bits/unique_ptr.h:398:4
#3 0x567f2d76ffcf in f1() /app/example.cpp:9:1
#4 0x567f2d770288 in main /app/example.cpp:20:5
#5 0x7583b0629d8f (/lib/x86_64-linux-gnu/libc.so.6+0x29d8f) (BuildId: 4f7b0c955c3d81d7cac1501a2498b69d1d82bfe7)
#6 0x7583b0629e3f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x29e3f) (BuildId: 4f7b0c955c3d81d7cac1501a2498b69d1d82bfe7)
#7 0x567f2d6863b4 in _start (/app/output.s+0x2e3b4)
Address 0x7183ae5f0040 is located in stack of thread T0 at offset 64 in frame
#0 0x567f2d76fe9f in f1() /app/example.cpp:3
This frame has 3 object(s):
[32, 40) 'p' (line 4)
[64, 68) 'a' (line 6) <== Memory access at offset 64 is inside this variable
[80, 88) 'ref.tmp' (line 7)
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: bad-free /app/example.cpp:9:1 in f1()
==1==ABORTING
```
Contributor guide
Assessment
This issue has not been assessed yet.