socumbersome
socumbersome

Reputation: 243

Can smart pointer be safer by disallowing automatic variables?

Let's consider such example:

#include <memory>

int main() {
    int x = 3;
    std::shared_ptr<int> p{&x};
    //std::shared_ptr<int> p = &x;
}

This program has a double-free bug (see also in action at: https://godbolt.org/z/T8eh13). If we were to comment out the line with p{&x} and uncomment the line below it, compilation fails, which is good and which I would expect as per https://stackoverflow.com/a/304169/1923988

The question I have is: could shared_ptr be implemented in a way to also protect us from usages like in the line with p{&x} (in general: usages of taking addresses of automatic variables)?

I imagine the answer is "no, because the callee sees only a pointer type, regardless of whether caller used & or a true pointer variable", but I wonder whether there truly is some fundamental limitation that would prevent compilers from distinguishing such two cases.

Upvotes: 0

Views: 58

Answers (1)

orlp
orlp

Reputation: 117761

Even passing local variables into smart pointers is a valid use-case.

Suppose you are using a C-style OOP API:

struct A { /* ... */ };
void init_a(A* a);
void destroy_a(A* a);

Then:

int main(int argc, char** argv) {
    A a;
    init_a(&a);
    std::unique_ptr<A, void(*)(A*)> a_raii(&a, destroy_a);
}

In theory the compiler should be able to detect in some scenarios that you are constructing a stdlib smart pointer using a pointer to a local variable without a custom deleter, but that would require quite some special code to detect one very specific bug in the giant landscape of C++ bugs.

Upvotes: 1

Related Questions