0
ここにnoobがあります。サッカーチームをシミュレートするプログラムを作成し、メモリ割り当ての処理を手助けします。私のプログラムは動作しますが、valgrindのは、私は問題が私の「クラブを破壊する」方法であるかもしれないと思うメモリリークが発生しましたが、割り当てられたメモリが割り当て解除されました
#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]);
}
}
}
を私はメソッド「create_player」でのメモリリークを持っていることを私に言ってと「add_player_to_club」されます。プレーヤー「オブジェクト」は「チーム」配列に格納されます。私は各プレーヤーオブジェクトのためにメモリを割り当て、チーム配列を繰り返して各インデックスを解放することによって割り当てを解除しました。私はどうしたの?
'クラブ - >サイズ= 0; for(i = 0; i < club->サイズ; i ++){'What。 – EOF
フォローアップ[this](http://stackoverflow.com/questions/38126544/printing-fields-of-structure-in-c-dynamic-memory-allocation) –