Angel Medina
Angel Medina

Reputation: 101

C: Segmentation fault when trying to create a list using malloc

I'm trying to create a list using malloc, the program gets integers that are input by the user, and it exits when the user inputs 0. However I'm getting the Segmentation fault (core dumped) error and I haven't been able to spot the problem. Things I have tried include adding the "liberar" method to free the memory but it doesn't work either. Thanks!

#include<stdlib.h>
#include<stdio.h>

struct list1 {
   int val;
   struct list1 * sig;
};

typedef struct list1 i;

void main() {
   i * aux, * cabeza;
   int entrada;

   cabeza = NULL;

   while(1) {
      aux = (i*)malloc(sizeof(i));
      scanf("%d\n",entrada);
      if(entrada==0){
          exit(0);
      }
      aux->val = entrada;
      aux->sig  = cabeza;
      cabeza = aux;
      liberar(cabeza);
   }

   aux = cabeza;

   while(aux) {
      printf("%d\n", aux->val);
      aux = aux->sig ;
   }
}

int liberar(struct list1* cabez)
{   
    struct list1 *temp;
    while (cabez != NULL)
    {
       temp = cabez;
       cabez = cabez->sig;
       free(temp);
    }

}

Upvotes: 0

Views: 89

Answers (1)

Goswin von Brederlow
Goswin von Brederlow

Reputation: 12332

Correcting all things from the comments (and a few unsaid things) you get this source:

#include<stdlib.h>
#include<stdio.h>
#include<assert.h>

typedef struct List {
    int val;
    struct List * next;
} List;

void list_free(List * list)
{   
    while (list != NULL)
    {
        List *temp = list;
        list = list->next;
        free(temp);
    }
}

int main() {
    List * aux, * result;
    int input;

    result = NULL;

    while(1) {
        scanf("%d",&input);
        if(input == 0){
            break;
        }
        aux = (List *)malloc(sizeof(List));
        assert(aux != NULL);
        aux->val = input;
        aux->next  = result;
        result = aux;
    }

    aux = result;

    printf("Result =\n");

    while(aux) {
        printf("%d\n", aux->val);
        aux = aux->next;
    }

    list_free(result);

    return 0;
}

Upvotes: 1

Related Questions