我在C语言中有这些结构。
typedef struct Game{
char* name;
char* team_1;
char* team_2;
int score[2];
} *pGame;
typedef struct Team{
char *name;
int victories;
} *pTeam;
typedef struct node_game{
pGame game;
struct node_game *next;
} *link_game;
typedef struct node_team{
pTeam team;
struct link_team *next;
} *link_team;
typedef struct head{
link_game game_list;
link_team team_list;
} *pHead;
还有这些函数
void initialize(pHead* heads,int m){
int i;
heads = (pHead*)malloc(m*sizeof(pHead));
for (i = 0; i < m; i++)
heads[i] = NULL;
}
//this function is to allocate dynamic memory for a string
char* str_dup(char* buffer){
char* str;
str = (char*) malloc(sizeof(char)*(strlen(buffer)+1));
strcpy(str,buffer);
return str;
}
void add_team(pHead* heads, char* name){
char* name_dup;
link_team new_team = (link_team) malloc(sizeof(struct node_team));
name_dup = str_dup(name);
new_team->team->name = name_dup; //this line gives me segmentation fault
}
int main(){
pHead* heads;
initialize(heads,M);
add_team(heads, "manchester");
return 0;
}
为什么add_team的最后一行会出现分段错误?我用VSC调试器看了一下,似乎应该很顺利。我的问题很可能是我在应该分配内存的时候没有分配内存,但我看不出是哪里的问题。另外,函数会做更多的东西,但它给我的分段故障已经有了)。
在你这样做的时候。
new_team->team->name = name_dup;
你为 new_team
但不是为了 new_team->team
. 这意味着 new_team->team->name
取消引用一个未初始化的指针,调用 未定义行为.
你需要先为它分配空间。
link_team new_team = malloc(sizeof(struct node_team));
new_team->team = malloc(sizeof(struct Team));
或者你可以改变 team
从 struct Team *
到 struct Team
并直接访问它。 你可能也想对 game
在 struct node_game
.