Why is my C code that uses queue giving Segmentation fault?

Asked

Viewed 62 times

1

Hello I must implement a queue that receives the name information and Cpf but only when I try to unroll something gives seg fault, without the row of the unroll wheel normal, but I do 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 anyone can tell me the mistake would help a lot, I thank you all already for the attention.

1 answer

2


You need to allocate memory to the queue as you are using a pointer to the queue (Queue*).
There may be other errors, I didn’t test how the program works, but surely the uninitialized pointer must 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;
}

Browser other questions tagged

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