How to use free in a structure variable (chained list)?

Asked

Viewed 323 times

1

I can’t use the free() in "struct Lista *proximo". Follows my code:

#include "stdafx.h"
#include <stdlib.h>
#include <conio.h>
#include <locale.h>

struct Lista {
    int num;
    struct Lista *proximo;
}celula;

int main()
{
setlocale(LC_ALL, "Portuguese");
//Criar uma função para a inserção de dados na lista

struct Lista *inicio;
struct Lista *proximo_item;
short int resp = 1;
short int cont = 1;

inicio = (struct Lista *)malloc(sizeof(struct Lista));
if (inicio == NULL) {
    exit(1);
}

proximo_item = inicio;
do {
    printf("Inf. um numero para a lista: ");
    scanf_s("%d", &proximo_item->num);
    printf("Deseja continuar? 1 = Sim | != Nao\n");
    scanf_s("%hi", &resp);
    system("cls");
    if (resp == 1) {
        proximo_item->proximo = (struct Lista *)malloc(sizeof(struct Lista));
        proximo_item = proximo_item->proximo;
    }
} while (resp == 1);

proximo_item->proximo = NULL;
proximo_item = inicio;
while (proximo_item != NULL){ 
    printf("%dº item da lista: %d\n", cont, proximo_item->num);
    proximo_item = proximo_item->proximo;
    cont++;
}
free(proximo);
free(inicio);
free(proximo_item);
_getch();
return 0;
}
  • In this case the fre() It’s not really necessary because the program is shutting down, but I understand that you want to do the right thing to use elsewhere, even though this algorithm is very naive for use in production. If you used the malloc() in a loop, the free() need to be in a loop as well. As you will not use anymore, maybe you could use inside the print loop, go printing and releasing. If there’s anything else you can do later, then you need a separate loop. It’s essentially browsing the list as it’s already done in the code and releasing instead of allocating, as it’s already been done.

1 answer

1


Change this:

free(proximo);
free(inicio);
free(proximo_item);

That’s why:

while (inicio != NULL) {
    struct Lista *deletando = inicio;
    inicio = inicio->proximo;
    free(deletando);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.