Game Development Community

Checking for null objects...

by Daniel Buckmaster · in Torque Game Engine · 07/22/2008 (5:53 am) · 3 replies

I've run into a strange problem when checking to see if a pointer refers to a null object. I have added some code to Projectile, and from onCollision, here's a fragment:
DecalData* decal = mCurrTick > mDataBlock->armingDelay ?
				mDataBlock->decals[idx] :
				mDataBlock->bounceDecals[idx];
			if(decal != NULL)
			{
				DecalManager *decalMngr = gClientSceneGraph->getCurrentDecalManager();
				if(decalMngr)
					decalMngr->addDecal(hitPosition, hitNormal, decal);
			}
The integer idx is defined and set beforehand. Now, it's entirely possible that idx is an illegal value. Shouldn't the if block catch this? In my case, idx was being set to -1, and the if evaluated as true, allowing the decal manager to try to create a decal with rubbish for a datablock.

I strongly suspect this is just my ignorance of C++ showing through - I've never been formally instructed, I've just learned by reading code.
I guess the simplest solution is to just make sure idx is a legal value, right?

EDIT: I tried something I'd seen done elsewhere. The if expression I changed to:
if(bool(decal))
Now the function works the way it should.
What's the difference between these two methods?

About the author

Studying mechatronic engineering and computer science at the University of Sydney. Game development is probably my most time-consuming hobby!


#1
07/22/2008 (6:48 am)
Quote:
Shouldn't the if block catch this?

If decals and bounceDecals are not some type of smart array object than an invalid value of IDX will cause you to read data outside of the allocated array bounds, in some cases causing GPFs or other such access violations.

The difference between the two if statements is nothing. They both verifiy that decal != NULL.

In conclusion, the part I think you are missing is whether or not accessing the decals and bounceDecals via the index-of operator will, in fact, give you NULL if your index (idx) is out of bounds.
#2
07/22/2008 (6:57 am)
Okay, thanks for clearing that up. I guess the answer, then, is to make sure idx makes sense.

Quote:The difference between the two if statements is nothing. They both verifiy that decal != NULL.
So I guess the second way worked because when I ran the engine the second time, the data outside the array was different, something that wouldn't cause a crash?
#3
07/22/2008 (7:01 am)
Correct.