#define SAFE_IF2( struct1, struct2, condition ) \
if ( struct1 \
&& struct1->struct2 \
&& struct1->struct2->condition )
#define SAFE_IF3( struct1, struct2, struct3, condition ) \
if ( struct1 \
&& struct1->struct2 \
&& struct1->struct2->struct3 \
&& struct1->struct2->struct3->condition )
#define VALID_PCHAR(ch) ( (ch) && (ch)->pcdata )
void do_something(struct char_data *ch)
{ if( VALID_PCHAR(ch) && ch->pcdata->whatever.bleh = =1 )
//dostuff;
return;
}
Take this for example:
Now, normally this wouldn't be any big issue, but consider, for whatever reason, 'ch' is a valid address in memory, but 'pcdata' is NULL, or better yet, both 'ch' and 'pcdata' are valid, but 'whatever' is NULL. When that's the case, if( ch->pcdata->whatever->blah == 1 ) is going to crash and burn.
What I'm getting at, is does anyone know how I might create a function to check for things like this?
Something like safe_if( ch->pcdata->whatever->blah == 1 ) that would check to see if each pointer it checks along the way and halts the execution of the function if it runs into a problem, rather than crashing the program.
I'm trying to avoid a bunch of checks that look like this:
if( ch && ch->pcdata && ch->pcdata->whatever )
{
if( ch->pcdata->whatever->blah == 1 )
do_something();
}
Maybe I'm going about this all wrong. I suppose it would be better in the long run to figure out how the data ended up invalid in the first place before the attempt to access it, but that's often difficult and time-consuming. Maybe there's a more fault-tolerant compilation options that I'm not aware of. Any ideas would be greatly appreciated.