-1

I've got an array of pointers as a member in my class. I am using those pointers to allocate a certain number of buffers.

In the destructor I want to free this memory, but it seems like I am doing something wrong.

   //In the Constructor
   for(int i = 0; i< NUM_OF_BUFFERS; i++)
   {
      mBuffer[i] = new Uint8[BUFFERSIZE];
      memset(mBuffer[i], 0, BUFFERSIZE);
      mBufferState[i] = NULL;
   }



   //In the destructor
   for (int i = 0; i < NUM_OF_BUFFERS; i++)
   {
      delete[] mBuffer[i];
   }

For some reason this doesn't seem to work. If I am commenting those lines in the destructor out, the program runs fine, if I run it with those lines it seems to freeze.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Simbi
  • 992
  • 3
  • 13
  • 29
  • forgot the member declaration! Uint8 *mBuffer[NUM_OF_BUFFERS]; – Simbi Jul 20 '12 at 21:03
  • 2
    The code looks fine. What does not work? You can also edit your own questions if you want to clarify something. – pmr Jul 20 '12 at 21:05
  • 7
    Do you have a copy constructor? – Seth Carnegie Jul 20 '12 at 21:06
  • 3
    For what it's worth, you could avoid the issue by not using dynamic memory management in the first place. Instead, use a `std::vector< std::vector > mBuffer;` and initialize it like `for ( int i = 0; i < NUM_OF_BUFFERS; ++i ) { mBuffer.push_back( std::vector( BUFFERSIZE ) ); }`. No work needed in the destructor. – Frerich Raabe Jul 20 '12 at 21:07
  • 4
    What Seth is really trying to say is [Look up the Rule of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). – chris Jul 20 '12 at 21:12
  • I don't have a copy constructor @Frerich Raabe I'll give it a try – Simbi Jul 20 '12 at 21:13
  • 2
    @user984308: If you "don't have one", then you actually do have one, but it's wrong, and you need to write a better one. Or stop writing code like it's C :-) – Kerrek SB Jul 20 '12 at 21:15
  • @user984308 Kerrek means that if you don't write a copy you'll be using the default, but if it's not working (and it easily happens as soon as you use pointers and structures)... you definitely need to write a custom one. – alcor Aug 23 '12 at 15:09

2 Answers2

2

Try to use some static analysis tool like cppcheck (it's free, multi platform and open source) and run it against your code.

You could even try PVS Studio if your code runs into Visual Studio (a very very nice tool).

alcor
  • 638
  • 1
  • 13
  • 27
1

There doesn't appear to be anything wrong with the code you posted, so the problem must be somewhere in the code you didn't post.

My bet would be on some out-of-bounds access that is clobbering the bookkeeping information required by the heap manager.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622