c linked list free memory

Linguaggi di programmazione: php, perl, python, C, bash e tutti gli altri.
shivi_ubuntu
Scoppiettante Seguace
Scoppiettante Seguace
Messaggi: 695
Iscrizione: venerdì 2 settembre 2011, 22:31

c linked list free memory

Messaggio da shivi_ubuntu »

volevo chiedervi quando uso la funzione malloc poi per liberare la memoria alla funzione free posso passare anche il metodo dentro quale ho allocato la memoria alle variabili oppure devo farlo una volta che return mi restituisce il dato dp return uso free() ? grazie mille

Codice: Seleziona tutto

#include <stdio.h>

// Creating struct for linked list

struct linkListNode{
    int data;
    struct linkListNode *next;
};


struct linkListNode *makeLinkListElements(){
    struct linkListNode *header = NULL;
    struct linkListNode *second = NULL;
    struct linkListNode *third = NULL;

    header = malloc(sizeof(struct linkListNode));
    second = malloc(sizeof(struct linkListNode));
    third = malloc(sizeof(struct linkListNode));

    header->data = 1;
    header->next = second;

    second->data = 2;
    second->next = third;

    third->data = 3;
    third->next = NULL;

    return header;
}

int getLinkListElementLength(struct linkListNode *linkListHeader){
    struct linkListNode *current = linkListHeader;
    int countLinkListElement = 0;
    while(current != NULL){
        countLinkListElement += 1;
        current = current->next;
    }

    return countLinkListElement;
}

void getLinkListLength(){
    struct linkListNode *lengthList = makeLinkListElements();
    int len = getLinkListElementLength(lengthList);
    printf("\t\tlink list length is %d \n",len);
}

int main(void)
{
    printf("\t\tLink List lesson\n");
    getLinkListLength();

    free(makeLinkListElements());
    return 0;
}
Avatar utente
SuperStep
Entusiasta Emergente
Entusiasta Emergente
Messaggi: 2037
Iscrizione: lunedì 19 dicembre 2011, 16:26
Desktop: Unity
Distribuzione: Ubuntu 16.04 LTS x86_64
Sesso: Maschile
Località: Somma Vesuviana (NA)

Re: c linked list free memory

Messaggio da SuperStep »

nel modo in cui hai fatto tu elimini liberi solamente l'aria di memoria allocata per il puntatore header...

se vuoi cancellare l'intera lista ti conviene farti una funzione apposta...

comunque puoi provare passando un puntatore per riferimento e copiando dentro "second" o "third" dopodiche' provare ad accedere a quell'indirizzo...
(e potrai perche' e' stato liberato solo header)
ubuntu 16.04 LTS 64-bit - Memoria: 31,3 Gib - Processore: Intel Core i7-5960X CPU @ 3.00 GHz × 16 - Grafica: AMD Radeon HD 7800 Series - Disco: SSD 256 GB x 4 (RAID 01)
Scrivi risposta

Ritorna a “Programmazione”

Chi c’è in linea

Visualizzano questa sezione: 0 utenti iscritti e 3 ospiti