Segmentation fault w / fwrite

I have a problem with a function fwrite

(I tested it with debug in C :: B). This is the code:

struct  studente
{   char Cognome_Nome[30];
    char Matricola [11];
    short Superati;
    float Media_Pesata;
    short Crediti;
};
typedef struct studente STUDENTE;

void main()
{   FILE *fp;
    STUDENTE Dati;

    if((fp = fopen("studente.dat","w+b")) == NULL)
        printf("Error\n");
    else
    {   fflush(stdin);
        printf("Inserire il cognome e nome: ");
        fgets(Dati.Cognome_Nome, 30, stdin);

        fflush(stdin);
        printf("\nInserire la matricola: ");
        fgets(Dati.Matricola, 11, stdin);

        fflush(stdin);
        printf("Inserire il numero di esami superati: ");
        scanf("%hd", &Dati.Superati);

        fflush(stdin);
        printf("Inserire la media pesata: ");
        scanf("%f", &Dati.Media_Pesata);

        fflush(stdin);
        printf("Inserire il numero di crediti: ");
        scanf("%hd", &Dati.Crediti);

        fwrite(&Dati, sizeof(STUDENTE), 1, fp);
    }
}

      

I am getting segmentation error when called fwrite

. I do not understand what the problem is. I checked the prototype fwrite

and I think everything is fine.

Thanks in advance.

+3


source to share


2 answers


Your compiler (like VC10 @alk) doesn't understand specifiers 'h'

in the format, which I believe are C99 additions. 3 solutions:

  • Change to new compiler.

  • Read short

    through a temporary variable.

    int i;
    scanf("%d", &i);
    Dati.Superati = i;
    
          

  • Make 2 fields int

    instead short

    and use"%d"

    struct  studente {
       ...
       int Superati;
       int Crediti;
    } 
    ...
    scanf("%d", &Dati.Superati);
    ...
    scanf("%d", &Dati.Crediti);
    
          




Other minor suggestions:

// @ Tom Tanner
// void main()
int main(void)

// Avoid magic numbers
// fgets(Dati.Cognome_Nome, 30, stdin);
fgets(Dati.Cognome_Nome, sizeof Dati.Cognome_Nome, stdin);

// @ Jeyaram
// Do not use fflush(stdin). Better methods exist to handle stray input data
// fflush(stdin);

// Less error prone and easier to maintain code
// fwrite(&Dati, sizeof(STUDENTE), 1, fp);
fwrite(&Dati, sizeof Dati, 1, fp);

// Check I/O function results

      

+1


source


What is likely happening:

Calling fgets()

or scanf()

causing data to be stored outside the structure Dati

. This stomps into a pointer variable fp

, which is probably saved right after Dati

in the stack frame. Then you call fwrite()

what difference fp

and arrow you have undefined behavior and segmentation fault.



I bet if you comment out all the functions scanf

and fgets

that are stored in Dati

and replace them with hard-coded field assignments Dati

, you will see that the glitch is fixed.

0


source







All Articles