Free memory of dynamic array of pointers in non-binary tree

Question:

I have this structure:

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

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

The function I use every time I go 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 free 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 freeing the memory the program stops and says that it must close.

So I ask myself: Am I declaring the children array correctly? and How can I free the memory?. Thanks a lot.

Answer:

Everything indicates that you are missing the line that I marked 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 off 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);
}

Keep in mind that if you make two memory reservations to create a node, you necessarily need two releases to avoid memory leaks.

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

Scroll to Top
AllEscort