Reputation: 11
I've been debugging this function for quite a while now and can't wrap my head around what could be going on with this piece of code.
void make_points(DocSpec instance, Tree *myTree, Point *p){
int i, j, k, index = 0;
for(i = 0; i < instance.numPt; i++)
{
p[i].x = instance.xCoordinates[i];
p[i].y = instance.yCoordinates[i];
p[i].parent = myTree[i].parent;
p[i].num_children = 0;
for(k = 0; k < MAX_NUM_CHILDREN; k++)
{
p[i].child[k] = 0;
}
for(j = 0; j < instance.numPt; j++)
{
if((i != j) && (myTree[j].parent == i))
{
p[i].num_children++;
p[i].child[index] = j;
index++;
}
}
p[i].overlap_hv = -1;
p[i].overlap_vh = -1;
index = 0;
}
printf("p[1].index = %d;\n", p[1].index);
printf("p[1].x = %d;\n", p[1].x);
printf("p[1].y = %d;\n", p[1].y);
printf("p[1].parent = %d;\n", p[1].parent);
printf("p[1].num_children = %d;\n", p[1].num_children);
printf("p[1].child[8] = {");
index = 0;
for(i = 0; i < MAX_NUM_CHILDREN; i++)
{
if(p[1].child[i] != 0 && index == 0)
{
printf("%d", p[1].child[i]);
}
elseif(p[1].child[i] != 0)
printf(", %d", p[1].child[i]);
}
print("};\n");
printf("p[1].overlap_hv = %d;\n", p[1].overlap_hv);
printf("p[1].overlap_vh = %d;\n", p[1].overlap_vh);
}
The output I'm getting after running the function is the following:
p[1].index = 1;
p[1].x = 0;
p[1].y = 90;
p[1].parent = 5;
p[1].num_children = 0;
p[1].child[8] = {1563515760, 1768448814, 945513580, 540876893};
p[1].overlap_hv = 909455739;
p[1].overlap_vh = 892679225;
But it should be:
p[1].index = 1;
p[1].x = 0;
p[1].y = 90;
p[1].parent = 5;
p[1].num_children = 0;
p[1].child[8] = {};
p[1].overlap_hv = -1;
p[1].overlap_vh = -1;
When I ran gdb on my program, I noticed that the values of p[1] are initialized properly, but when
printf("p[1].x = %d;\n", p[1].x);
is executed - p[1].child[4], p[1].child[5], p[1].child[6], p[1].child[7], p[1].overlap_hv, p[1].overlap_vh all get overwritten with the garbage values.
I have no idea why or how a printf statement could change the values of my struct members.
Any help would be greatly appreciated.
Upvotes: 0
Views: 687
Reputation: 11
Turns out I didn't use the proper typecast when reallocating memory. A quick check with Valgrind led me right to the culprit.
had
p = (Point*) realloc(p, instance.numPt * sizeof(p));
and this fixed it
p = (Point*) realloc(p, instance.numPt * sizeof(Point));
Thanks to all for the suggestions.
Upvotes: 1
Reputation: 6298
My guess is that index
is crossing child boundary and j
overwrites next struct members p[1].overlap_hv
and p[1].overlap_vh
:
p[i].child[index] = j;
index++;
Upvotes: 0