Search code examples
cpointersstructsegmentation-faultfgets

segmentation fault w/ fgets using struct


i'm still a beginner with coding; i'm writing a code to learn about structs and pointers but i get a segmentation fault when using fgets. here's the code

 #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <malloc.h>
#include <string.h>
#include <stdbool.h>
#define a 100
#define MAX 200

int i;
typedef struct libreria{
    char titolo[a];
    char autore[a];
    int anno;
    char genere[a];
}libro;

libro *libroptr;
int inserisci_libro(libro *libroptr){
    printf("Titolo: \n");
    fgets((libroptr->titolo),a,stdin); // here is where i get the error
    printf("Autore: \n");
    fgets((libroptr->autore),a,stdin);
    printf("Anno: ");
    scanf("%i",&libroptr->anno);
    printf("Genere: ");
    fgets((libroptr->genere),a,stdin);

    return 0;
};

void main(){
    //printf("%d\n",sizeof(libroptr->titolo));
    typedef struct libreria libro[MAX];
    inserisci_libro(libroptr);
    return;
}

the idea is to create a library of book that the user have to insert. once i run the code i get the error on the fgets in the function inserisci_libro but i can't understand why. if someone can help thanks a lot.


Solution

  • You defined a null pointer

    libro *libroptr;
    

    and this null pointer is used to access memory as for example

    fgets((libroptr->titolo),a,stdin);
    

    So the program has undefined behavior.

    You should define an object of the type libro in main as for example

    libro libro_uno;
    

    and pass a pointer to it to the function

    inserisci_libro( &libro_uno );
    

    And this declared typedef name as an alias for an array type

    typedef struct libreria libro[MAX];
    

    is not used in your program and will only confuse readers of the program because in the file scope there is already declared the alias libro for the structure type struct libreria.

    Pay attention to that according to the C Standard the function main without parameters shall be declared like

    int main( void )