| Issue |
164963
|
| Summary |
[LifetimeSafety] Detect lifetime safety issues in placement new and manual destructor calls
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
SidneyCogdill
|
https://godbolt.org/z/d5cPd7hsW
```cpp
#include <iostream>
#include <string>
constexpr auto long_string = "Test42Test42Test42Test42Test42";
int main() {
alignas(std::string) char storage[sizeof(std::string)];
std::string* str = new (storage) std::string{long_string};
std::cout << *str << '\n';
str->~basic_string();
std::cout << *str << '\n'; // Use after destruction
}
```
https://godbolt.org/z/c6zYMz1Y8
```cpp
#include <string>
constexpr auto long_string = "Test42Test42Test42Test42Test42";
int main() {
std::string a{long_string};
a.~basic_string();
} // <- implicit ~basic_string() invocation here; causes double free
```
Similarly, in C++ `std::construct_at` and `std::destroy_at` can be used for in-place construction/destruction but that's probably much more complicated to detect in a generalized way.
```cpp
#include <iostream>
#include <string>
constexpr auto long_string = "Test42Test42Test42Test42Test42";
int main() {
alignas(std::string) char storage[sizeof(std::string)];
std::string* str = std::construct_at((std::string*)storage, long_string);
std::cout << *str << '\n';
std::destroy_at(str);
std::cout << *str << '\n'; // Use after destruction
}
```
Other than the "use after destruction" there is also the "construction before destruction" issue:
```cpp
#include <iostream>
#include <string>
int main() {
alignas(std::string) char storage[sizeof(std::string)];
std::string* str1 = new (storage) std::string{"Old"};
auto p1 = str1->c_str();
std::string* str2 = new (storage) std::string{"New"}; // Construction overwriting existing object
std::cout << p1 << '\n';
}
```
I'm not sure if it can be made to detect this class of bugs under the current framework of Clang LifetimeSafety implementation. But I'll leave the code snippet here to raise the awareness.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs