malloc'd指针偶尔出现分段错误

时间:2013-04-12 14:53:34

标签: c pointers struct malloc fault

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

任何帮助解决这个问题都将受到赞赏。

2 个答案:

答案 0 :(得分:2)

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

Player one=malloc(sizeof(Player));

Player被定义为指向player_t结构的指针,因此您没有保留足够的内存来保留整个结构。只有第一个指针(name)才足以让您在访问nickname时看到崩溃。

尝试:

Player one=malloc(sizeof(struct player_t));

答案 1 :(得分:1)

one->nickname=malloc(strlen(name)+1);
...
strcpy(one->nickname,nickname);

如果nickname超过name会怎样?