"Segmentation Fault" in Double Linked List

0

I hope you can help me visualize the error in the following code.

I've been studying all types of lists lately. In this program I focus on inserting an element at the beginning of a DOUBLY LINKED list. As soon as I started studying these types of lists, I started doing something simple.

The problem is that when executing the program through GDB, a warning appears in the CMD saying that the program has a SEGMENTATIO FAULT in the function that performs the insertion to the list.

The code is shown below.

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

struct elementos
{
    int dato;
    struct elementos *anterior;
    struct elementos *siguiente;
};
typedef struct elementos Nodo;
void insertarElemento(Nodo **cabeza, int x);
void mostrarElementos(Nodo * cabeza);
int main()
{
    Nodo *primero = NULL;

    insertarElemento(&primero, 45);
    mostrarElementos(primero);
    return 0;
}

void insertarElemento(Nodo **cabeza, int x)
{
    Nodo *nuevo_nodo = (Nodo*)malloc(sizeof(Nodo));
    nuevo_nodo -> dato = x;
    nuevo_nodo -> siguiente = *cabeza;
    nuevo_nodo -> anterior = NULL;
    (*cabeza) -> anterior = nuevo_nodo;
    *cabeza = nuevo_nodo;
}

void mostrarElementos(Nodo *cabeza)
{
    while(cabeza != NULL)
    {
        printf("%8d", cabeza -> dato);
        cabeza = cabeza -> siguiente;
    }
}
    
asked by Jesús Fragoso 04.04.2018 в 03:37
source

1 answer

2
void insertarElemento(Nodo **cabeza, int x)
{
    Nodo *nuevo_nodo = (Nodo*)malloc(sizeof(Nodo));
    nuevo_nodo -> dato = x;
    nuevo_nodo -> siguiente = *cabeza;
    nuevo_nodo -> anterior = NULL;
    (*cabeza) -> anterior = nuevo_nodo; // <<---
    *cabeza = nuevo_nodo;
}

If the list is empty, (*cabeza)->anterior is an invalid operation ... you are missing a conditional:

if( NULL != cabeza )
  (*cabeza)->anterior = nuevo_nodo;
    
answered by 04.04.2018 / 07:39
source