I'm trying to create a multiway binary tree from a parent array. The structure for my multiway binary tree nodes is the following:

typedef struct x{
    int id;
    struct x* son[MAX];
    int index;
}nodeR2;

I use this function to allocate memory and it works fine:

nodeR2* allocMem(int id)
{
    nodeR2* n = new nodeR2;
    if(n)
    {
        n->id = id;
        n->index = 0;
        for(int i = 0 ; i < MAX ; i++)
            n->son[i] = NULL;
        return n;
    }
    else
        return NULL;
}

I use this function to create a node for every index in the initial array:

{
    if(createdNodes[id-1] != NULL) // if the node has already been created, we do not need to create it again
        return;
    
    createdNodes[id-1] = allocMem(id); // if the node is not created, we create it 
    if(v[id-1] == -1) // if it is the root (the parent of the node is -1) then we assign it to the root
    {
        root = createdNodes[id-1]; 
        return;
    }

    if(createdNodes[v[id-1]] == NULL) // if parent does not exist, we call this function again for the parent
        createNode(v, v[id-1], createdNodes, root);
    
    // if parent exist, assing current node to its sons
    
    nodeR2* n = createdNodes[v[id-1]];

    addToSons(n, createdNodes[id-1]);    
}

And I use this function to add a son to the respective parent:

void addToSons(nodeR2* source, nodeR2* son)
{
    source->son[source->index++] = son;
}

Then it throws me "segmentation fault" error. When I look into the debugger, I find that when addToSons(n, createdNodes[id-1]); is executed for the first time, n is 0x0 in memory, causing the segmentation error.
Why n turns into 0x0 if before the execution of that line, it has other value? And why after we return from the CALL STACK the value of n changes?

0

There are 0 answers