0

This is how i allocate dynamic memory for a 2D array

char **twod;

twod=new char*[count];
for (int i = 0; i < count; i++)
{
    twod [i] = new char [MAX];
}

This is how i release the memory for a 2D array

for (int i=0; i<count;i++)
  {
      delete [] twod [i];

  }
   delete [] twod;

How do i know i have successfully released everything and there is no memory leak???

Computernerd
  • 7,378
  • 18
  • 66
  • 95
  • 7
    You could always just use RAII and have a much lower probability of a memory leak occurring to start with. – chris Jan 27 '13 at 07:00
  • *"How do i know i have successfully released everything and there is no memory leak???"* - Because you have called `delete []` for everything you used `new []` to allocate. And what @chris said. – Ed S. Jan 27 '13 at 07:02
  • 1
    `This is how i allocate dynamic memory for a 2D array` I am sorry to hear that. Be sure to take your pills... – Lightness Races in Orbit Jan 27 '13 at 08:29
  • What chris said. Prevention is better than cure: http://stackoverflow.com/a/959708/24283 – timday Jan 27 '13 at 08:53

1 Answers1

4

Ways to tell if you have successfully released dynamic allocated memory

Run the code in valgrind or any such memory leak detection tool.
If you want you could also overload the new and delete operators for your class and do the bookeeping yourself but that it too much effort so you are much better off setting with a memory leak detection tool.

Ofcourse I consider the example only an sample example and not the code one will usually go for because:

  1. You are better off avoiding dynamic allocations, use automatic variables instead.
  2. If you must then use smart pointers with RAII and not raw pointers.
Alok Save
  • 202,538
  • 53
  • 430
  • 533