realloc崩溃在以前稳定的功能

Suk*_*asa 0 c++ windows breakpoints realloc visual-studio-2008

显然SDL_Mixer中的这个功能一直在死,我不知道为什么.有没有人有任何想法?根据visual studio的说法,崩溃是由Windows在realloc()行的某处触发断点引起的.

有问题的代码来自SDL_Mixer的SVN版本,如果这有所不同.

static void add_music_decoder(const char *decoder) 
{ 
  void *ptr = realloc(music_decoders, num_decoders * sizeof (const char **)); 
  if (ptr == NULL) { 
    return; /* oh well, go on without it. */ 
  } 
  music_decoders = (const char **) ptr; 
  music_decoders[num_decoders++] = decoder; 
} 
Run Code Online (Sandbox Code Playgroud)

我正在使用Visual Studio 2008,music_decoders和num_decoders都是正确的(music_decoders包含一个指针,字符串"WAVE"和music_decoders.ptr是0x00000000,我能说的最好,崩溃似乎在realloc中()函数.有没有人知道如何处理这个崩溃问题?我不介意做一些重构以使这项工作,如果它归结为那.

Ste*_*sop 5

首先,分配一个num_decoders指针数组,然后写入num_decoders该数组中的索引是无效的.大概是第一次调用这个函数时,它分配了0个字节并写了一个指向结果的指针.这可能破坏了内存分配器的结构,导致在realloc调用时出现崩溃/断点.

顺便说一句,如果你报告错误,请注意add_chunk_decoder(在mixer.c中)以相同的方式被破坏.

我会替换

void *ptr = realloc(music_decoders, num_decoders * sizeof (const char **));
Run Code Online (Sandbox Code Playgroud)

void *ptr = realloc(music_decoders, (num_decoders + 1) * sizeof(*music_decoders)); 
Run Code Online (Sandbox Code Playgroud)