Search code examples
arrayscmemory-managementlinked-listfree

Linked list inside an array deallocation in C


I have these structs:

typedef struct Nodo{
    int id_nodo;
    struct Nodo *next;
} Nodo;


typedef struct{
    Nodo *head;
} inmap;


//Struct Grafo

typedef struct {
    int N; // numero dei nodi del grafo
    int *out; // array con il numero di archi uscenti da ogni nodo
    inmap *in; // array con gli insiemi di archi entranti in ogni nodo
} grafo;

I have a graph that contains a pointer to an array of inmap elements (which are the heads of the linked lists).

The deallocation function that I made is this one:

// Funzione per deallocare tutti i nodi della lista
void dealloca_lista(inmap *lista) {
    // Ppuntatore ausiliario per scorrere la lista
    Nodo *corrente = lista->head;

    // Ciclo per scorrere ogni nodo della lista
    while (corrente != NULL) {
        // Salvo il puntatore al prossimo nodo
        Nodo *prossimo = corrente->next;

        // Dealloco la memoria occupata dal nodo corrente
        free(corrente);

        // Aggiorno il puntatore al nodo corrente con il prossimo
        corrente = prossimo;
    }

    // Imposto l'head della lista a NULL
    lista->head = NULL;
}

It works but in this way I'm freeing all the nodes of every list, the inmap struct is still allocated (for every position of the array g.in).

The following function is used to create every node:

inmap crea_lista() {
    inmap *nuova_lista = (inmap*)malloc(sizeof(inmap));
    if (nuova_lista != NULL) {
        nuova_lista->head = NULL;
    }
    return *nuova_lista;
}

I tried freeing all the inmap struct in the array using free(&g.in[i]) in a for loop, but I get segmentation fault.


Solution

  • g.in is an array of structs, not an array of pointers, so you don't need to free the elements.

    Since crea_lista() returns the list by value, it doesn't need to use malloc(), and then you don't need to free anything.

    inmap crea_lista() {
        inmap nuova_lista = {NULL};
        return nuova_lista;
    }