-
Notifications
You must be signed in to change notification settings - Fork 15.1k
Open
Labels
clang:temporal-safetyIssue/FR relating to the lifetime analysis in Clang (-Wdangling, -Wreturn-local-addr)Issue/FR relating to the lifetime analysis in Clang (-Wdangling, -Wreturn-local-addr)
Description
https://godbolt.org/z/d5cPd7hsW
#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
#include <string>
constexpr auto long_string = "Test42Test42Test42Test42Test42";
int main() {
std::string a{long_string};
a.~basic_string();
} // <- implicit ~basic_string() invocation here; causes double freeSimilarly, 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.
#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:
#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.
Metadata
Metadata
Assignees
Labels
clang:temporal-safetyIssue/FR relating to the lifetime analysis in Clang (-Wdangling, -Wreturn-local-addr)Issue/FR relating to the lifetime analysis in Clang (-Wdangling, -Wreturn-local-addr)
Type
Projects
Status
No status