c free()崩溃:没有可用于“ntdll!RtlpNtEnumerateSubKey()

时间:2016-12-05 20:05:50

标签: c eclipse

当我尝试释放我的对象时,我的程序在Eclipse上崩溃了--PokemonTrainer。我在this article尝试了解决方案,但它没有帮助。

PokemonTrainer pokemonTrainerCreate(char* name, Pokemon initial_pokemon,
    int max_num_local, int max_num_remote)
{
    PokemonTrainer trainer = malloc(sizeof(PokemonTrainer));

    if ((name == NULL) || (initial_pokemon == NULL) || (trainer == NULL) ||
        (max_num_local < 0) || (max_num_remote < 0))
        return NULL;

    char tmp_name[strlen(name)];
    strcpy(tmp_name, name);
    trainer->name = tmp_name;
    trainer->max_num_local = max_num_local;
    trainer->max_num_remote = max_num_remote;
    trainer->pokemons_local = malloc(sizeof(Pokemon)
        trainer->max_num_local);
    trainer->pokemons_remote = malloc(sizeof(Pokemon)
        trainer->max_num_remote);

    if (trainer->pokemons_remote == NULL) {
        free(trainer->pokemons_local);
        return NULL;
    } else if (trainer->pokemons_local == NULL) {
        free(trainer->pokemons_remote);
        return NULL;
    }

    trainer->pokemons_local[0] = pokemonCopy(initial_pokemon);
    trainer->curr_num_local = 1;
    trainer->curr_num_remote = 0;

    return trainer;
}

void pokemonTrainerDestroy(PokemonTrainer trainer)
{
    if (trainer == NULL)
        return;

    if (trainer->curr_num_local > 0)
        for (int i = trainer->curr_num_local - 1; i >= 0; i--)
            pokemonDestroy(trainer->pokemons_local[i]);

    if (trainer->curr_num_remote > 0)
        for (int i = trainer->curr_num_remote - 1; i >= 0; i--)
            pokemonDestroy(trainer->pokemons_remote[i]);

    free (trainer);  // here it's crashed
}

在堆栈中执行free()期间,我得到了“ntdll没有可用的源代码!RtlpNtEnumerateSubKey()0x77cf04e5”错误。

1 个答案:

答案 0 :(得分:1)

PokemonTrainer trainer = malloc(sizeof(PokemonTrainer));不太可能正常工作,因为你要分配指针的大小,而不是真实的数据。

您的存储空间不足=&gt;发生了未定义的行为,并且在释放内存(损坏的内存列表)时会发生这种情况

我会这样做:

 PokemonTrainer trainer = malloc(sizeof(*PokemonTrainer));

因此sizeofPokemonTrainer所示结构指向的大小。

编辑:为了完整性,BLUEPIXY建议你在这里丢失1个字节(因为空终止字符):

char tmp_name[strlen(name)]; 
strcpy(tmp_name, name);

而且这个分配的空间是暂时的,所以我建议:

char *tmp_name = strdup(name);

将分配正确的大小并执行动态分配,即使在从例程返回后仍保持有效。