我有以下代码,每当我尝试释放我的 malloc 内存时,我有时会遇到分段错误。此错误仅在释放与我的某些结构成员相关的内存时发生(仅在昵称及以上),这意味着我从未遇到过分段错误free(player->name)
,但大约有一半的时间我从其他两个释放中获得分段错误(查看仪器如何为空,没有效果)
typedef struct player_t {
char * name;
char * nickname;
Instrument * instruments;
int instrumentAmount;
} * Player;
Player playerCreate(const char* name, const char* nickname,
int maxInstruments) {
Player one=malloc(sizeof(Player));
if(one==NULL || !checkLegalName(name)|| !checkLegalName(nickname) || maxInstruments<=0) {
return NULL;
}
one->name=malloc(strlen(name)+1);
one->nickname=malloc(strlen(name)+1);
if(!one->name || !one->nickname) {
playerDestroy(one);
return NULL;
}
strcpy(one->name,name);
strcpy(one->nickname,nickname);
one->instrumentAmount=maxInstruments;
one->instruments=NULL;
return one;
}
其次是:
void playerDestroy(Player player) {
if( !player) {
return;
}
free(player->name);
free(player->nickname); // this is where it happens.
free(player->instruments);
free(player);
}
解决此问题的任何帮助将不胜感激。