Skip to content

[LifetimeSafety] Detect lifetime safety issues in placement new and manual destructor calls #164963

@SidneyCogdill

Description

@SidneyCogdill

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 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.

#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

No one assigned

    Labels

    clang:temporal-safetyIssue/FR relating to the lifetime analysis in Clang (-Wdangling, -Wreturn-local-addr)

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions