I think you are looking at the wrong direction. You probably have a bug by which you are not correctly initializing the pointers, deleting the objects too early and trying to reuse the pointer after it has been deleted or something alike. If that is the case, you should focus on determining why that is happening and fixing the bug, rather than trying to find a way of hiding the bug.
As of the approach that you are using with the typeid
operator, the answer is that it is not valid. For objects of types that don't contain virtual functions, the typeid
operator is resolved at compile time based on the static type of the pointer. For objects that contain at least one virtual function, it is resolved at runtime, but calling typeid(p)
with an invalid pointer is undefined behavior, and in the same way that it seems to work it might crash.
The use of smart pointers that has been suggested, might depend on what the library actually does and whether you can pass around the smart pointers at all times or not. In general it is a good idea to use smart pointers for memory management, and that will in turn guarantee that the pointers will be correctly initialized (fix if the problem is initialization) and because you no longer delete
manually, chances are that if the problem is with early deletion that will no longer happen. But note that while this might solve the issue, I still think that you need to understand why the pointer is invalid in your application, as that might be a symptom of a greater problem.
Now, on the original question of how to check whether the pointer is dangling or not, you cannot do it in the program, but you can run your program inside memory debuggers (valgrind in linux, Purify or a set of others in linux) and the tool will be able to help you determining whether the pointer was never initialized, or if you released the memory to the system before the incorrect use.