gpt4 book ai didi

c free() 崩溃 : No source available for "ntdll! RtlpNtEnumerateSubKey()

转载 作者:行者123 更新时间:2023-11-30 19:10:42 24 4
gpt4 key购买 nike

当我尝试释放我的对象 - PokemonTrainer 时,我的程序在 Eclipse 上崩溃。我已尝试 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() 期间,我收到“No source available for "ntdll!RtlpNtEnumerateSubKey() at 0x77cf04e5”错误。

最佳答案

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

您将没有足够的存储空间 => 会发生未定义的行为,对于您来说,它会在释放内存时发生(损坏的内存列表)

我会这样做:

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

因此sizeof采用PokemonTrainer指向结构的大小。

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

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

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

char *tmp_name = strdup(name);

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

关于c free() 崩溃 : No source available for "ntdll! RtlpNtEnumerateSubKey(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40982417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com