Release dynamic array memory from pointers in non-binary tree

4

I have this structure:

typedef struct Nodo 
{
    int valor;
    int numSubNodos;
    struct Nodo *padre;
    struct Nodo **hijo;
} Nodo; 

To fill it as a non-binary unbalanced tree, or rather a node can have several children and not all the nodes have the same number of children.

The function that I use every time I am going to create a node is this:

Nodo *crearNodo (Nodo *padre, int numSubNodos, int valor)
{

    Nodo *node;
    node =  (Nodo *)malloc(sizeof(Nodo));
    //printf( "Nodo creado: %d\n", node);
    node->valor = valor;
    node->padre = padre;
    if (numSubNodos > 0)
        node->hijo =  malloc( numSubNodos * sizeof(Nodo*) );    
    else
        node->hijo = NULL;
    return node;

}

And to release the memory I use this other function:

int freeNodos (Nodo *node)
{

    if (node == NULL)
        return 0;

    for (int i = 0; i < nodo->numSubNodos; i++)
        freeNodos(nodo->hijo[i]);
    free (node);
}

The program stores the values and prints them, however at the moment of releasing the memory the program stops and says that it must be closed.

Then I ask myself: Am I declaring the children array well? and How can I free the memory? Thank you very much.

    
asked by Jacobo Córdova 05.04.2017 в 16:29
source

1 answer

3

Everything points to the fact that you are missing the line that marked you with the comment.

Nodo *crearNodo (Nodo *padre, int numSubNodos, int valor)
{

    Nodo *node;
    node =  (Nodo *)malloc(sizeof(Nodo));
    //printf( "Nodo creado: %d\n", node);
    node->valor = valor;
    node->padre = padre;
    node->numSubNodos = numSubNodos; // <<--- AQUI
    if (numSubNodos > 0)
        node->hijo =  malloc( numSubNodos * sizeof(Nodo*) );    
    else
        node->hijo = NULL;
    return node;

}

And well, to finish the play ... you need a free :

int freeNodos (Nodo *node)
{

    if (node == NULL)
        return 0;

    for (int i = 0; i < nodo->numSubNodos; i++)
        freeNodos(nodo->hijo[i]);
    free(node->hijo); // <<--- AQUI
    free(node);
}

Think that if you make two memory reserves to create a node you need two releases to avoid memory leaks.

By the way, note that freeNodos should return an integer and return nothing.

    
answered by 05.04.2017 / 16:33
source