0

I`m trying to do a linked list, but it's giving me segmentation fault error.

Here`s code:

typedef struct{
  char diretor[50];
  char nome[50];
}Filme;

typedef struct{
  Filme filme;
  struct Nodo *proximoNodo;
}Nodo;

void inserirFinal(Nodo **nodo_inicial)
{
  Nodo *novo_nodo, *iterador;
 
  iterador = *nodo_inicial;

  novo_nodo = malloc(sizeof(Nodo));
  adicionarNovoFilme(novo_nodo);
  novo_nodo->proximoNodo = NULL;

  if(iterador == NULL)
    *nodo_inicial = novo_nodo;
  else
  {
    while(iterador != NULL)
      iterador = iterador->proximoNodo;

    iterador->proximoNodo = novo_nodo;
  }
}

void adicionarNovoFilme(Nodo *nodo)
{
  Filme filme;

  printf("Diretor:");
  gets(filme.diretor);
  printf("Nome:");
  gets(filme.nome);

  nodo->filme = filme;
}

The code should insert a new node at the end of a linked list (if it was empty, it started one) The method would receive a pointer to a pointer that would be the iterator of the list in the main. I'm don't know why it's giving segmentation error.

Mateus
  • 64
  • 4
  • It would be nice if this was a [mcve] to make it easy to copy/paste, compile, and run to duplicate the issue you're having. – Retired Ninja Dec 09 '22 at 00:41
  • Obligatory: [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/q/1694036/13843268). – sj95126 Dec 09 '22 at 00:43

1 Answers1

2
    while(iterador != NULL)
      iterador = iterador->proximoNodo;

stops when iterador == NULL. So when you then do

iterador->proximoNodo = novo_nodo;

you're dereferencing a null pointer.

You need to change the condition to:

while (iterador->proximoNodo != NULL)

This will stop when iterador points to the last node, it won't go past it.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • but in this case, the while will not get the last node, because the last will be iterador->proximoNodo == NULL, but i want access it too – Mateus Dec 09 '22 at 11:52
  • The last node is the one whose next node is NULL. So this DOES get to the last node. This is the one that you want to change to point to the new node. – Barmar Dec 09 '22 at 16:47