Deleting dynamic arrays properly

In previous postings, i was made aware that i was probably not deleting my dynamically allocated arrays properly. I'm purposely not using vectors here, for good reasons, otherwise i'd most certainly would be doing so.

So, i've created two arrays:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

// --------- array1 --------

NNArray = new int*[n];
    
  for(int i = 0; i < n; i++)  // this creates the m X n array
  {
     NNArray[i] = new int[choose];
  }


// --------- array2 --------


  DistanceArray1 = new float*[n-1];

  for (int i = 0; i < n - 1; i++)
  {
    DistanceArray1[i] = new float[n-1-i]; // this creates an array which has a decreasing amount of columns per row.....
  }
 




so - i just want to make sure that i'm deleting this arrays properly when i've finished with them. So here are my attempts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

// deleting array1 

  for (int i = 0; i < n-1; i++)
    delete [] DistanceArray1[i];

  delete [] DistanceArray1;

// and deleting array2

  for (int i = 0; i < choose; i++) 
  {
    delete [] NNArray[i];
  }

  delete [] NNArray;  




does this look correct? is there a way for me to check?



All these can be checked using memory debugging tools (there are various names people call these tools with). These tools detect memory leaks in your code.

Memory leak happens when you allocate memory but forget to delete it.

Valgrind is nice tool to detect memory leaks in your code. This is free. There are many commencial alternatives like purify for unix, bounds checker for windows.

http://valgrind.org/
Topic archived. No new replies allowed.