Why is my code in C using queue giving segmentation fault?

1

Hello, I have to implement a queue that receives the name and cpf information, but only when I try to dequeue something does it give a fault, without the line of the normal dialer, but I can not see the error in it.

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

typedef struct{
    long int cpf;
    char nome[45];
} Dados;

typedef struct No_fila {
    Dados info ;
    struct No_fila *prox ;
} No_fila ;

typedef struct Fila {
   No_fila *inicio ;
   No_fila *fim ;
} Fila ;

void criar_fila ( Fila *f ) {
   f-> inicio = NULL ;
   f-> fim = NULL ;
}

void enfileirar ( Fila *f , Dados x) {
  No_fila *novo = ( No_fila *) malloc( sizeof ( No_fila ));

  novo->info = x;
  novo -> prox = NULL ;
  if (f -> fim == NULL ){
    f -> inicio = novo ;
  }
  else{
      f -> fim -> prox = novo ;
  }
  f -> fim = novo ;
}

void desenfileirar ( Fila *f , Dados *v) {
   if (f -> inicio != NULL ){
       *v = f->inicio->info ;
       No_fila *p = f->inicio ;
       f->inicio = f->inicio->prox ;
       free (p) ;
       if (f -> inicio == NULL )
           f -> fim = NULL ;
   }
}

void exibir_fila(Fila *f){
    No_fila *aux = f->inicio;
    while (aux != NULL){
       printf("%ld,%s \n", aux->info.cpf,aux->info.nome);
       aux = aux->prox;
    }
    printf("\n");
}

int main(){
  Dados teste1,teste2,*teste3;
  Fila *fila;
  teste1.cpf = 10987654321;
  strcpy( teste1.nome, "João");
  teste2.cpf = 12345678910;
  strcpy( teste2.nome, "Maria");
  criar_fila(fila);
  enfileirar(fila,teste1);
  enfileirar(fila,teste2);
  exibir_fila(fila);
  desenfileirar(fila,teste3); 
  printf("%ld,%s",teste3->cpf,teste3->nome);
  return 0;
}

If someone can tell me the error would help a lot, thank you all for the attention.

    
asked by anonymous 20.10.2018 / 17:04

1 answer

2

You need to allocate memory for the queue, since you are using a pointer to queue (Row *). There may be other errors, I have not tested the program, but the uninitialized pointer should be causing the error in question.

// nao esquecer dos includes!!!

#include <stdio.h>  // para printf
#include <stdlib.h> // para malloc

int main() {
  Dados teste1, teste2, *teste3 = malloc(sizeof(Dados)); // <-------------
  Fila *fila = malloc(sizeof(Fila)); // <---------------------------------
  teste1.cpf = 10987654321;
  strcpy(teste1.nome, "João");
  teste2.cpf = 12345678910;
  strcpy(teste2.nome, "Maria");
  criar_fila(fila);
  enfileirar(fila, teste1);
  enfileirar(fila, teste2);
  exibir_fila(fila);
  desenfileirar(fila, teste3); 
  printf("%ld,%s", teste3->cpf, teste3->nome);
  return 0;
}
    
20.10.2018 / 17:36