hello can some one please explain me how to do error handling in a recursive function. for eg. the following is a recursive function :
Code:
void subdivide_kdtree(kdnode *kd, mesh *m, int depth, int maxdepth, int maxtriangles, int axis)
{
int i, nextaxis;
kd->child[0] = kd->child[1] = NULL;
trinode *ptr, *last;
if(kd->ntriangles > maxtriangles && depth < maxdepth)
{
for(i = 0; i < 2; i++)
{
kd->child[i] = malloc(sizeof(kdnode));
kd->child[i]->box = kd->box;
kd->child[i]->trifirst = NULL;
kd->child[i]->ntriangles = 0;
kd->splitplane = axis;
kd->child[i]->box.minB.coord[axis] = kd->box.minB.coord[axis] + 0.5 * i * (kd->box.maxB.coord[axis] - kd->box.minB.coord[axis]);
kd->child[i]->box.maxB.coord[axis] = kd->box.minB.coord[axis] + 0.5 * (i+1) * (kd->box.maxB.coord[axis] - kd->box.minB.coord[axis]);
nextaxis = (axis + 1) % 3;
ptr = kd->trifirst;
while(ptr != NULL)
{
if(insidebox(kd->child[i], m, ptr->tindex, axis, i))
{
add_to_triangle_list(&kd->child[i]->trifirst, &last, ptr->tindex);
kd->child[i]->ntriangles += 1;
}
ptr = ptr->next;
}
subdivide(kd->child[i], m, depth + 1, maxdepth, maxtriangles, nextaxis);
}
}
}
Notice the bolded part. If malloc fails I usually do error handlling by passing a flag which indicates an error has happened and i also print an error message. just for the sake of an example:
Code:
int some_function(void)
{
double *p;
int flag = 0;
p = malloc(sizeof(*p) * 500);
if(p == NULL)
{
fprintf(stderr, "\n%s line %d : Memory allocation failure\n", __FILE__, __LINE__);
flag = 1;
return flag;
}
return flag;
}
I mean how to pass this flag in a recursive function is what i can't figure out. pls help me out.