Search code examples
ccoredumpkdtree

KdTree C implementation resulting in core dump


I'm dealing with a core dump issue to which whom I cannot find a solution. Any kind of help would be appreciated 'cause I'm getting hopeless.

I assume the error appears when getting to the second execution of the building function but I'm clueless what's the fuss about.

http://pastebin.com/XwW33VY8

struct node *BuildKdTree(struct point *S, int d, int n)
{
    struct node *v;

    if(n==1)
    {
        v->l.x=S[0].x;
        v->l.y=S[0].y;
    }
    else
    {
        int i, n1, n2;
        float mE, mV;
        struct point *S1, *S2;

        S1=(struct point*)malloc(sizeof(struct point)*(n));
        S2=(struct point*)malloc(sizeof(struct point)*(n));

        if(d%2 == 0)
        {
            bubbleSortX(S, n);
            mV=medianValueX(S, n);
            v->l.x=mV;
            mE=medianElement(n);

            for(n1=0;n1<(int)mE;n1++)
            {
                S1[n1]=S[n1];
            }

            for(n2=0, i=(int)mE;i<n;n2++, i++)
            {
                S2[n2]=S[i];
            }
        }
        else
        {
            bubbleSortY(S, n);
            mV=medianValueY(S, n);
            v->l.y=mV;
            mE=medianElement(n);

            for(n1=0;n1<(int)mE;n1++)
            {
                S1[n1]=S[n1];
            }

            for(n2=0, i=(int)mE;i<n;n2++, i++)
            {
                S2[n2]=S[i];
            }
        }

        v->leftChild=BuildKdTree(S1, d+1, n1);
        v->rightChild=BuildKdTree(S2, d+1, n2); 
    }

    return v;
}

Thank you in advance.


Solution

  • You declare the variable v as a pointer to struct node, but you don't initialize this pointer. Uninitialized local (non-static) variables have an indeterminate value.

    Using an uninitialized local (non-static) variable leads to undefined behavior, which is a very common reason for crashes.

    Modern compilers are good at detecting the use of uninitialized variables, and warn about them. You might have to enable extra warnings though, so when using e.g. gcc add the flag -Wall and you should get a warning about this.