我有以下代码,其中每当我试图释放malloc’ed内存时,有时会出现分段错误。这个错误只发生在释放与我的一些结构成员相关联的内存时(仅在昵称和其他成员上(,这意味着我从未得到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);
}
如有任何帮助,我们将不胜感激。
您的(主(问题在这一行:
Player one=malloc(sizeof(Player));
Player被定义为指向Player_t结构的指针,因此您没有保留足够的内存来保存整个结构。这只够第一个指针(name
(使用,这就是访问nickname
时出现崩溃的原因。
尝试:
Player one=malloc(sizeof(struct player_t));
one->nickname=malloc(strlen(name)+1);
...
strcpy(one->nickname,nickname);
如果nickname
比name
长怎么办?