Amirhessam
Amirhessam

Reputation: 154

How to check whether a memory allocation is still valid?

I have some shared pointers in my c++ program. After I allocate memory to the pointers (using new), I do some stuff in my program and then I need to know if some other modules have deleted these pointers or not. Because if a pointer has been deleted then I would get an access violation read error. Is there any function or any way to check this out?

Upvotes: 0

Views: 228

Answers (1)

John Dibling
John Dibling

Reputation: 101456

I guess that when you say "shared pointer" you are not referring to an actual smart pointer class like std::shared_ptr or boost:shared_ptr, but simply a raw pointer which is passed from function to function.

There is no reliable, safe, and cross-platform way to determine the validity of a raw pointer.

However, using smart pointer classes will relieve much of the burden of managing dynamic memory. Instead of passing around raw pointers, you pass around smart pointers. These smart pointers (at least the shared_ variety) are reference-counted. As long as at least one reference to the pointer still exists, the object being pointed to will not be deleted. Once the last reference is removed, the object is automatically deleted.

The smart_ptr I reference above has a so-called "strong reference" to the controlled object. There are also smart pointer which maintain a weak reference to the controlled object. These weak pointers do not prevent the object from being deleted, and can be checked for validity before using the controlled object.

Take a look at the documentation for more information.

Upvotes: 3

Related Questions