Re: How do you detect and handle invalid pointers?
"DeMarcus" <use_my_alias_here@hotmail.com> wrote in message
news:4ccfcc35$0$23763$14726298@news.sunsite.dk...
Hi,
How do you detect and handle invalid pointers to avoid segmentation fault?
I have a callback scenario that looks like this. (using C++0x)
#include <functional>
#include <string>
#include <iostream>
#include <vector>
class SomeObject
{
public:
void fnc( const std::string& text )
{
std::cout << text << std::endl;
}
};
int main()
{
std::vector<std::function<void()> > callbacks;
SomeObject* s = new SomeObject;
callbacks.push_back( std::bind( &SomeObject::fnc, s, "Hello" ) );
callbacks.push_back( std::bind( &SomeObject::fnc, s, "World" ) );
callbacks.push_back( std::bind( &SomeObject::fnc, s, "The End" ) );
std::vector<std::function<void()> >::iterator i = callbacks.begin();
std::vector<std::function<void()> >::iterator end = callbacks.end();
for( int n = 0; i != end; ++i, ++n )
{
(*i)(); // Run the callback.
// At some point during this loop s is deleted. Could be from
// another thread.
if( n == 1 )
delete s;
}
return 0;
}
This callback trouble is just an example, but how are invalid pointers
detected in general? Is there a smart pointer that can handle this? Like
throwing an exception or just not run the callback.
apart from detecting NULL pointers, usually validation is uncommon.
usually, an entirely invalid pointer showing up somewhere expected is
uncommon apart from programmer error, and hence the crash is usually not
such a bad thing (in many cases, it will point right to the source of the
error).
better is to try to write decent code, rather than rely on cheap tricks to
try to make it work.
the segfault is itself an exception (of sorts), hence one can catch it and
use this to detect the invalid pointer.
on Linux/... there is "signal()", but it is a hassle to use (and signal does
not usually respect threads).
on Windows, one can use SEH, which is a little nicer.
there are ways to validate pointers, but they have drawbacks:
typically, they depend on a specific context, such as validating that a
pointer is into a custom-managed heap (via checking address ranges);
often, they may involve OS specific facilities;
the logic may become complex or slow for certain non-trivial cases (IOW,
where one actually tries to check where a pointer points to, rather than
"defer and see if it blows up", or "check if page is mapped", or similar);
....
how to implement any of this will not be described here for now though...