Problem with Segmention fault

Asked

Viewed 46 times

0

I was studying a little bit, I’m very beginner in programming, and I came across a mistake, the segmention default, I will drop my code, and if possible, someone can figure out why I’m getting this error.

NOTE: The error comes right after typing age.

//Leitura de arquivo
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  FILE *arq;

  arq = fopen("arq.txt", "a");

  if(arq == NULL) {
    printf("Erro na abertura do arquivo.");
    return 0;
  } else {

  struct fichaAluno {
    char nome[50];
    char disciplina[50];
    int idade;
    float primNota;
    float segNota;
  };

      struct fichaAluno aluno;

      printf("\t====================================================");
      printf("\n\t\t\tCADASTRO DE ALUNO\n");
      printf("\t====================================================");
      printf("\n\n\t\t\tNOME: ");
      fgets(aluno.nome, 50, stdin);
      fprintf(arq, "%s", aluno.nome);

      printf("\n\t\t\tDISCIPLINA: ");
      fgets(aluno.disciplina, 50, stdin);
      fprintf(arq, "%s", aluno.disciplina);

      printf("\n\t\t\tIDADE: ");
      scanf("%d", aluno.idade);
      fprintf(arq, "%d", &aluno.idade);

      printf("\n\t\t\tPRIMEIRA NOTA: ");
      scanf("%f", aluno.primNota);
      fprintf(arq, "%f", &aluno.primNota);

      printf("\n\t\t\tSEGUNDA NOTA: ");
      scanf("%f", &aluno.segNota);
      fprintf(arq, "%f", &aluno.segNota);



      printf("\t====================================================");
      printf("\n\t\t\tVERIFICAR ALUNO\n");
      printf("\t====================================================");
      printf("\n\n\t\t\tNOME: %s", aluno.nome);
      printf("\n\t\t\tDISCIPLINA: %s", aluno.disciplina);
      printf("\n\t\t\tIDADE: %d\n", aluno.idade);
      printf("\n\t\t\tPRIMEIRA NOTA: %.1f\n", aluno.primNota);
      printf("\n\t\t\tSEGUNDA NOTA: %.1f\n", aluno.segNota);

      return 0;

      fclose(arq);
    }
}

1 answer

1

Segmentation fault is an error that occurs when you try to access (read or write) an address in RAM that is reserved for another program (or the operating system itself) or that does not exist.

In case you are assigning value to student.age variable incorrectly. Continue using scanf, but do so:

scanf("%d", &aluno.idade);

You must inform the scanf the address of the variable in which you want to save the read value.

Source: https://en.wikipedia.org/wiki/Segmentation_fault

Browser other questions tagged

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