Home > Mobile >  Segmentation fault using multiple structs
Segmentation fault using multiple structs

Time:12-13

I'm kinda new in C. I'm having some trouble using pointers and stuff like that.

I made this piece of code to try to understand why does it return me Segmentation Fault.

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

typedef struct lligada {

    int userID;

    struct lligada *prox;

} *LInt;

typedef struct {

   int repo_id;
   LInt users;

} Repo;


typedef struct nodo_repo {

   Repo repo;

   struct nodo_repo *left; 
   struct nodo_repo *right; 

} *ABin_Repos;



void createList (int id_user, int id_repo) {
   ABin_Repos temp = malloc(sizeof(struct nodo_repo));

   temp->repo.repo_id = id_repo;
   temp->repo.users->userID = id_user;

   temp->left = NULL;
   temp->right = NULL;

   printf("%d", temp->repo.users->userID);
}

int main() {
 
    int id_user, id_repo;

    scanf("%d %d", &id_user, &id_repo);

    createList(id_user, id_repo);

  return 0;
}

I really don't understand. Sorry if this is a stupid question.

Thank you!

CodePudding user response:

The type of users is LInt and LInt is an alias of type struct lligada *:

typedef struct lligada {
    int userID;    
    struct lligada *prox;
} *LInt;

That means the type of users is struct lligada *.
In the createList(), you are accessing users pointer before allocating it. Hence, you are getting segmentation fault.

You should do:

void createList (int id_user, int id_repo) {
   ABin_Repos temp = malloc(sizeof(struct nodo_repo));

   // Allocate memory to users
   temp->repo.users = malloc (sizeof (struct lligada));
   // check malloc return
   if (temp->repo.users == NULL) {
       // handle memory allocation failure
       exit (EXIT_FAILURE);
   }

   temp->repo.repo_id = id_repo;
   temp->repo.users->userID = id_user;

   .....
   .....

Additional: Follow good programming practice, make sure to check returned value of function like scanf() and malloc().

  • Related