C noob在这里。创建了一个模拟足球队的程序,帮助我掌握内存分配。我的程序有效,但valgrind告诉我,方法“create_player”和“add_player_to_club”中有内存泄漏
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 8
typedef struct player {
int id;
char *position;
} Player;
typedef struct club {
int size;
Player *team[SIZE];
} Club;
Player *create_player(int id, const char *description);
void create_team(Club *club);
void print_club(const Club *club);
void destroy_player(Player *player);
void add_player_to_club(Club *club, int id, const char *position);
void destroy_club(Club *club);
int main() {
Club club;
create_team(&club);
add_player_to_club(&club, 1, "forward");
add_player_to_club(&club, 2, "goalie");
print_club(&club);
destroy_club(&club);
return 0;
}
Player *create_player(int id, const char *description){
Player *player;
player = malloc(sizeof(Player));
if(description == NULL){
player->position = NULL;
} else {
player->position = malloc(strlen(description) + 1);
strcpy(player->position, description);
player->id = id;
}
return player;
}
void destroy_player(Player *player){
if (player == NULL){
return;
} else {
free(player->position);
free(player);
}
}
void create_team(Club *team){
team->size = 0;
}
void print_club(const Club *club) {
int i = 0;
if (club == NULL) {
return;
} else if (club->size == 0) {
printf("No team members\n");
} else {
for (i = 0; i < club->size; i++) {
printf("Id: %d Position: %s\n", club->team[i]->id,
club->team[i]->position);
}
}
}
void add_player_to_club(Club *club, int id, const char *position){
if (club == NULL || club->size >= SIZE) {
return;
} else {
club->team[club->size] = create_player(id, position);
club->size++;
}
}
void destroy_club(Club *club){
int i = 0;
if (club == NULL) {
return;
} else {
club->size = 0;
for (i = 0; i < club->size; i++) {
destroy_player(club->team[i]);
}
}
}
我认为问题可能出在我的“破坏俱乐部”方法上。玩家“对象”存储在“团队”数组中。我为每个玩家对象分配了内存,并通过迭代团队数组并释放每个索引来解除分配。我搞砸了什么?
答案 0 :(得分:2)
在destroy_club
中,您将size
设置为0,然后使用它来循环播放器,因此它不会循环播放。
在清理玩家后将size
设为0 :
for (i = 0; i < club->size; i++) {
destroy_player(club->team[i]);
}
club->size = 0;