使用多个结构的分段错误
Segmentation fault using multiple structs
我是 C 语言的新手。我在使用指针之类的东西时遇到了一些麻烦。
我制作这段代码是为了试图理解为什么会出现 return 我的分段错误。
#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
并且 LInt
是类型 struct 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()
.
等函数的返回值
我是 C 语言的新手。我在使用指针之类的东西时遇到了一些麻烦。
我制作这段代码是为了试图理解为什么会出现 return 我的分段错误。
#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
并且 LInt
是类型 struct 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()
.