c++ - Is there any way to check if pointer is dangling? -
i have code use pointer access datablock. in rare cases, few members of datablock empty, , result pointer becomes dangling. in fact, correct pointer program crashes when trying pointer.
the usual advice avoid type of usage. sadly, framework use requires use type of data access methods.
is there way can "check" if pointer invalid before doing operation it? checking pointer not equal null did not work, obviously. tried this:
try { cstring csclassname = typeid(*pmypointer).name(); // check error condition // line below fails due dangling pointer (data block not valid). hr = pmypointer->mypointermethod(); } catch(bad_typeid) { return e_fail; } catch(...) { return e_fail; }
is correct way?
i think looking @ wrong direction. have bug not correctly initializing pointers, deleting objects , trying reuse pointer after has been deleted or alike. if case, should focus on determining why happening , fixing bug, rather trying find way of hiding bug.
as of approach using typeid
operator, answer is not valid. objects of types don't contain virtual functions, typeid
operator resolved @ compile time based on static type of pointer. objects contain @ least 1 virtual function, resolved @ runtime, calling typeid(p)
invalid pointer undefined behavior, , in same way seems work might crash.
the use of smart pointers has been suggested, might depend on library , whether can pass around smart pointers @ times or not. in general idea use smart pointers memory management, , in turn guarantee pointers correctly initialized (fix if problem initialization) , because no longer delete
manually, chances if problem deletion no longer happen. note while might solve issue, still think need understand why pointer invalid in application, might symptom of greater problem.
now, on original question of how check whether pointer dangling or not, cannot in program, can run program inside memory debuggers (valgrind in linux, purify or set of others in linux) , tool able determining whether pointer never initialized, or if released memory system before incorrect use.
Comments
Post a Comment