Destructor for multi-dimension array

Hello,
I have written the following destructor:

1
2
3
4
5
6
7
 
ImportCSV::~ImportCSV()
{
	for (int i = 0; i < righe-firstRow;i++)
		delete [] price[i];
	delete [] price;
}


The variable to be "destructed" has been created as:
1
2
3
4
5
6
7
8
void  ImportCSV::setPrice()
{
	
	price = new double*[righe-firstRow];
		for (int i = 0; i<righe-firstRow;i++)
			price[i]=new double[elem-firstCol];

}


Everything works fine until the destructor is called, then I receive an error message (program xx.exe has started an interruption point) and the program stops.
Any suggestion on what is wrong with the destructor?

Many thanks

Does anything happen between the constructor and the destructor? Does it crash if all you do is create it an destroy it?
What is the constructor for ImportCSV? What is price defaulted to? What are rhe and firstRow set to?

Your destructor traverses through elements of the price array when it may not have been instantiated. I would put lined 4 -6 of your destructor inside a if (price != NULL) check, or something like that.

There are other potential problems, depending on how you implemented your class.
- If you call setPrice twice, the original price and all it's contained arrays would be leaked.
- Can righe and firstRow be modified? That could cause memory leaks or accessing unallocated memory.

Have you considered using STL vectors instead of the arrays?
doug4 wrote:
I would put lined 4 -6 of your destructor inside a if (price != NULL) check, or something like that.
That won't help if he didn't properly initialize the pointer and it is a dangling pointer.
Thank you for the suggestion L_B.
If I call the destructor without populating the array it works.
I have found an error in this phase and now it works.
Thank you

Topic archived. No new replies allowed.