Search code examples
c++windowsvisual-studio-2008breakpointsrealloc

realloc crashing in previously stable function


Apparently this function in SDL_Mixer keeps dying, and I'm not sure why. Does anyone have any ideas? According to visual studio, the crash is caused by Windows triggering a breakpoint somewhere in the realloc() line.

The code in question is from the SVN version of SDL_Mixer specifically, if that makes a difference.

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; 
} 

I'm using Visual Studio 2008, and music_decoders and num_decoders are both correct (music_decoders contains one pointer, to the string "WAVE", and music_decoders. ptr is 0x00000000, and the best I can tell, the crash seems to be in the realloc() function. Does anyone have any idea how I could handle this crash problem? I don't mind having to do a bit of refactoring in order to make this work, if it comes down to that.


Solution

  • For one thing, it's not valid to allocate an array of num_decoders pointers, and then write to index num_decoders in that array. Presumably the first time this function was called, it allocated 0 bytes and wrote a pointer to the result. This could have corrupted the memory allocator's structures, resulting in a crash/breakpoint when realloc is called.

    Btw, if you report the bug, note that add_chunk_decoder (in mixer.c) is broken in the same way.

    I'd replace

    void *ptr = realloc(music_decoders, num_decoders * sizeof (const char **));
    

    with

    void *ptr = realloc(music_decoders, (num_decoders + 1) * sizeof(*music_decoders));