0

我有以下代码,每当我尝试释放我的 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);
}

解决此问题的任何帮助将不胜感激。

4

2 回答 2

2

您的(主要)问题出在这一行:

Player one=malloc(sizeof(Player));

Player 被定义为指向 player_t 结构的指针,因此您没有保留足够的内存来保留整个结构。仅对第一个指针 ( name) 就足够了,这就是您在访问时看到崩溃的原因nickname

尝试:

Player one=malloc(sizeof(struct player_t));
于 2013-04-12T15:17:48.997 回答
1
one->nickname=malloc(strlen(name)+1);
...
strcpy(one->nickname,nickname);

如果nickname长于name怎么办?

于 2013-04-12T15:15:55.513 回答