Crash on function call? (Solved)

Posted By: TehV

Crash on function call? (Solved) - 10/11/12 15:49

Hi,
In one of my projects, I continue to encounter a problem I cannot seem to solve. I've spotted where the problem comes from, but I can't see what causes it. The culprit is this function:
Code:
function assign(ENTITY* unit,ENTITY* targ,var todo) {
	sys_marker("001");
	VECTOR* to;	
	var temp1;
	var temp2;
	if (unit != NULL && todo >= 0) {
		if (targ != NULL) {
			unit.parent = targ;
			unit.skill12 = 1;
			unit.skill20 = todo;
			unit.skill21 = 1;
		} else {
			unit.parent = NULL;
			unit.skill12 = 1;
			unit.skill20 = todo;
			temp1 = mouse_pos3d.z;
			temp2 = temp1 / -mouse_dir3d.z;
			vec_set(to,mouse_dir3d);
			vec_scale(to,temp2);
			vec_add(to,camera.x);
			
			vec_set(unit.skill15,to);
			unit.skill21 = 1;
		}
	} else {
		if (unit != NULL) {
			unit.parent = NULL;
			unit.skill12 = 0;
			unit.skill20 = 0;
			unit.skill21 = 1;
		}
	}
	sys_marker("002");
}



This is where I call up the function:
Code:
if (key_m) {
	sys_marker("014");
	mouse_map = cursor2;
	sys_marker("017");
	if (isClick) { sys_marker("018"); assign(temp_ent,mouse_ent,1); }
	sys_marker("003");
}



The function runs fine with any combination of parameters, but I get an error ("Crash in main: 018") when I attempt to call 'assign' after the second parameter was NULL once. The function is used to assign tasks to individual entities, and it is absolutely neccesary that this function works without any problems.
Does someone have any idea why this might be happening?
Thanks in advance!
~TehV

EDIT: Changed title. Problem was solved.
Posted By: Uhrwerk

Re: Crash on function call? - 10/11/12 16:32

You forgot to initialize "VECTOR* to". In the inner else clause you then overwrite random memory with "vec_set(to,mouse_dir3d);" and the following lines.
Posted By: TehV

Re: Crash on function call? - 10/11/12 17:20

Thanks! It now runs perfectly fine. I'll assume the same goes for any data type, and make sure my variables, strings, variables, etc. are initialized as well.
Posted By: Uhrwerk

Re: Crash on function call? - 10/11/12 19:12

Yes. It's a good habit to initialize any pointer immediately when declaring it, either to NULL or to a valid address. This can save you tons of headaches.

To make your code absolutely bullet proof you should also check mouse_dir3d.z before dividing by it. It could be zero and hence cause a division by zero error. It's not that this is very likely but you never know... ;-)
Posted By: TehV

Re: Crash on function call? - 10/11/12 20:10

I did that as well, thanks for pointing that out. Since mouse_dir3d.z should never be positive (I'm 'tracing' down to a flat plane at z=0 and the camera is always higher than z=0) I simply filtered out anything that is not facing down.
© 2024 lite-C Forums