From 278867b3c8ae44e54901c63eaa5b729cd7832a55 Mon Sep 17 00:00:00 2001 From: Josh Holtrop Date: Sat, 21 May 2011 23:20:50 -0400 Subject: [PATCH] AV::Sound copies sound buffer to avoid memory leak --- src/AV.cc | 9 ++++++++- src/AV.h | 1 + src/Engine.cc | 8 +++----- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/AV.cc b/src/AV.cc index 128db20..75b91e8 100644 --- a/src/AV.cc +++ b/src/AV.cc @@ -244,6 +244,7 @@ AV::Sound::Sound(AV & av) m_ss = NULL; m_buff_bytes_left = 0; m_volume = 1.0f; + m_data = NULL; } AV::Sound::~Sound() @@ -252,11 +253,17 @@ AV::Sound::~Sound() { Sound_FreeSample(m_ss); } + if (m_data != NULL) + { + delete[] m_data; + } } bool AV::Sound::load(unsigned char *data, unsigned int size) { - m_rwops = SDL_RWFromMem(data, size); + m_data = new unsigned char[size]; + memcpy(m_data, data, size); + m_rwops = SDL_RWFromMem(m_data, size); Sound_AudioInfo desired; desired.channels = CHANNELS; desired.format = AUDIO_S16SYS; diff --git a/src/AV.h b/src/AV.h index cd2c3f2..cc0a80e 100644 --- a/src/AV.h +++ b/src/AV.h @@ -38,6 +38,7 @@ class AV void setVolume(float v); protected: AV & m_av; + unsigned char *m_data; SDL_RWops * m_rwops; Sound_Sample * m_ss; int m_loop_count; diff --git a/src/Engine.cc b/src/Engine.cc index 2909d0b..62209bd 100644 --- a/src/Engine.cc +++ b/src/Engine.cc @@ -641,12 +641,10 @@ int Engine::loadSound(const string & name) unsigned char *data = loadFile(nm.c_str(), &size); if (data != NULL) { - if (avs->load(data, size)) - { - /* TODO: memory leak, fix with buffer */ - return addSound(avs); - } + bool loaded = avs->load(data, size); free(data); + if (loaded) + return addSound(avs); } cerr << "error loading sound '" << name << "'" << endl; }