thp9
thp9

Reputation: 376

How to check if a pointer still points to valid memory in C++?

I have a pointer which equals to another pointer

I'd like to check if my pointer equals to a pointer which is not null.

int* ptr0 = new int(5);
int* ptr1 = ptr0;

delete ptr0;

if ( ?? )
{
    std::cout << "ptr1 equals to a null ptr" << std::endl;
}

What should I write in the condition ?

Knowing that:

Upvotes: 3

Views: 1150

Answers (3)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

delete does not result in a null pointer. It results in a dangling pointer, which is undetectable in general. So, you cannot.

Upvotes: 1

ppl
ppl

Reputation: 1120

Use a shared_ptr<T> combined with a weak_ptr<T>.

For example,

int main() {
    std::tr1::shared_ptr<int> ptr0(new int);
    std::tr1::weak_ptr<int> ptr1_weak(ptr0);

    *ptr0 = 50;

    // Depending on if you reset or not the code below will execute
    //ptr0.reset();

    if (std::tr1::shared_ptr<int> ptr1 = ptr1_weak.lock()) {
        std::cout << "Changing value!" << std::endl;
        *ptr1 = 500;
    }
}

Upvotes: 6

Cubic
Cubic

Reputation: 15683

You can't. While in theory you could, depending on the implementation of new, check if the memory pointed to is currently in use there's no way to confirm that it's still the same object you were originally pointing to using only raw pointers.

You can use C++11 smart pointers to do something kinda like that, but I really don't think that's what you actually wanna do here.

Upvotes: 1

Related Questions