Array Deletion

Whenever An array is deleted with the code below I get the following message:

HEAP[week5.exe]: Invalid address specified to RtlValidateHeap( 00E60000, 009EF9D4 ) week5.exe has triggered a breakpoint.

 
  delete [] arr;


When I delete it with this code it runs OK
 
delete arr[0];	delete arr[1];


I don't entirely understand why I have to delete the contents of the array indvidually
Here is the full code:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
 class Array
{
	int *values;
	int size;
public:
	Array(int siz)
	{
		size = siz;
		values = new int[size];
		std::cout << "Array of " << size << " ints constructed." << std::endl;
		
	}

	void Put(int ix, int val)
	{
		values[ix] = val;
	}

	int Get(int count)
	{  return values[count]; }

	~Array()
	{
		delete[]values;
		std::cout << "Array of " << size << " ints destructed." << std::endl;
	}

};


int main(void)
{
	Array *arr[2] = { new Array(2), new Array(2) };

	for (int i = 0; i < 2; i++)
		for (int j = 0; j < 2; j++)
			arr[i]->Put(j, j + 10 + i);

	for (int i = 0; i < 2; i++)
		for (int j = 0; j < 2; j++)
			std::cout << arr[i]->Get(j) << std::endl;

	delete [] arr;


	system("pause");
	return 0;
}


delete should only be used on pointers pointing to things that has been created with new.

arr is an array of two Array pointers. It has not been created with new so you should not try to destroy it with delete. Instead it will be automatically destroyed when the function ends.

arr[0] and arr[1] are pointing to Array objects that has been created with new so it is on them you should use delete.
Ok makes absolute sense

Appreciate it.
Topic archived. No new replies allowed.