【问题标题】:Segmentation fault using multiple structs使用多个结构的分段错误
【发布时间】:2022-01-16 14:23:16
【问题描述】:

我是 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;
}

我真的不明白。 对不起,如果这是一个愚蠢的问题。

谢谢!

【问题讨论】:

  • 我会通过 valgrind 之类的工具运行你的程序,它应该会告诉你出了什么问题。
  • 字段:Lint users; 是指向结构的指针。对于lligada 结构,您需要使用malloc。值得花时间学习如何使用调试器检查数据是否存在此类错误。

标签: c struct segmentation-fault


【解决方案1】:

users 的类型是LIntLIntstruct 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;

   .....
   .....

补充: 遵循良好的编程习惯,确保检查函数的返回值,如 scanf()malloc()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 2021-02-07
    • 2018-03-29
    • 1970-01-01
    • 2011-08-24
    • 2020-02-17
    • 2014-01-18
    相关资源
    最近更新 更多