簡體   English   中英

使用多個結構的分段錯誤

[英]Segmentation fault using multiple structs

我是 C 的新手。 我在使用指針和類似的東西時遇到了一些麻煩。

我編寫了這段代碼試圖理解為什么它會返回分段錯誤。

#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;
}

我真的不明白。 對不起,如果這是一個愚蠢的問題。

謝謝!

users的類型是LInt ,而LIntstruct lligada *類型的別名:

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

這意味着users的類型是struct lligada *
createList()中,您在分配users指針之前訪問它。 因此,您遇到了分段錯誤。

你應該做:

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;

   .....
   .....

附加:遵循良好的編程習慣,確保檢查 function 的返回值,如scanf()malloc()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM