2016-12-05 5 views
-1

私のオブジェクトを解放しようとしたときに私のプログラムが夢中になりました - PokemonTrainer.Iは解決策をthis articleで試してみましたが、役に立たなかった。c free()クラッシュ: "ntdll!RtlpNtEnumerateSubKey()のソースがありません

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 
} 

それは私がNTDLL!RtlpNtEnumerateSubKey()0x77cf04e5で 『エラー「なしソースが利用できる』取得していますスタック内の空き()の実行中にあります。

+1

char tmp_name [strlen(name)]; 'char tmp_name [strlen(name)+1];' trainer-> name = tmp_name; 'はこの関数以外では無効です。 – BLUEPIXY

+1

'trainer-> pokemons_local = malloc(sizeof(Pokemon) トレーナー - > max_num_local);'それはコンパイルされますか? '*'が欠けていませんか? –

答えて

1

PokemonTrainer trainer = malloc(sizeof(PokemonTrainer));は、実際のデータではなくポインタのサイズを割り当てているため、正常に動作する可能性は低いです。

あなたは十分なストレージを持っていない=>未定義の動作が発生し、メモリ(壊れたメモリリスト)を解放するとき、あなたのためにそれが起こる

私はこれを行うだろう:

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

のでsizeof構造体のサイズはであり、PokemonTrainerとなります。

EDIT:完全を期すため、BLUEPIXYが(理由はNULL終端文字の)あなたはここに1つのバイトを逃してきたことを示唆している:

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

しかも、この割り当てられたスペースは一時的なものであるので、私はお勧めしたい:

char *tmp_name = strdup(name); 

正しいサイズを割り当て、ルーチンから戻った後でも有効なままである動的割り当てを実行します。

関連する問題