Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

pointers

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:

  • I don't want to set nullptr any of the ptr's after removal
  • I don't have access to ptr0 in my condition
like image 820
thp9 Avatar asked Jan 22 '26 00:01

thp9


2 Answers

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;
    }
}
like image 50
ppl Avatar answered Jan 24 '26 13:01

ppl


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.

like image 20
Cubic Avatar answered Jan 24 '26 15:01

Cubic