Why is there an error when deleting an array of pointers to class object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void listDA::ExpandArray()
{
	_size++;	
	Product **newarray=new Product*[_size];
	for(int i=0;i<(_size-1);i++)
	{
		newarray[i]=_arr[i];
	}
	newarray[_size-1]=NULL;

	delete [] _arr;
	_arr = newarr;

}


This function is to expand an dynamic array of pointer to object of Product class.

There is an error at "delete [] _arr".

Why is there such an error?

Thank you for your answer. :))

You guys are going to help me a lot!
Last edited on
Hi

What are you doing at line 7 ? and What are you doing at line 11 ? Does it make sense to you ?
What is the exact error message?

I'm guessing that _arr is an array of pointers? In this case I do not understand that rock over on the seventh throw.
@L B

L B wrote
In this case I do not understand that rock over on the seventh throw.


I don't get you, If you ask me some thing, could you please be more clear ?
closed account (zb0S216C)
Two things I see wrong:

1) You've got a memory leak with newarray since you never pair it with delete[ ].
2) If _arr is dynamically allocated 2-D array, each pointer within newarray now share the memory held by the pointers within _arr. When delete[ ] is used by newarray, it'll delete the memory held by _arr's pointers, leaving them dangling.

Wazzak
Framework, did you really skip over line 12 like that?
closed account (zb0S216C)
Hmm.. I must have. Apologies.

Wazzak
This is not 2D array... but it is a dynamic array of pointer to objects of Product class.

In line 7, i try to copy address of pointer to another dynamic array of pointer.

In line 11, i try to prevent memory leak but the addresses of pointers are already copied to newarray, so there should be no problem. Is my understanding correct?

Anyway, I still don't understand why there is a runtime error. :( Could you explain more to me :))

And thanks a lot for your helps :)
Last edited on
You probably fucked up an invariance. Use std::vector instead.
The error 'is not' there, but something that you did before. So, isolation and step by step debugging.

I guess that Product does not have a default constructor. To know how std::vector resolves that check out allocators (placement new)
Last edited on
Topic archived. No new replies allowed.