C++ Using delete on 2D-Vector of a struct with float arrays
I have a struct like this:
struct foo {
int a,b,c;
float d;
float *array1;
float *array;
};
And now I us开发者_JAVA百科e this struct for a 8x8 2D-Vector like this:
vector< vector<foo> > bar(8);
for (int i = 0; i < 8; i++)
bar[i].resize(8);
Within my program, "bar" is now filled with data, for example:
bar[1][5].array1 = new float[256];
bar[1][5].array2 = new float[256];
// Et cetera.
How can I free the memory used by bar correctly?
I tried a for-loop for freeing every float array like this:
delete [] bar[i][j].array1;
But that will result in a heap exception on runtime.
Add a destructor to your struct
to clean up those members.
Alternatively you could do as Eduardo León suggests and allocate them as part of the structure.
float array1[256];
instead of
float *array1;
First of all, you ought to use vector<float>
instead of float*
, arrays are evil.
Second, the way you are freeing the memory is correct, the mistake must be at some other place.
Can you post an actual code fragment? If you're deleting just the elements you're allocating, there shouldn't be a problem.
I'd suggest a couple things to help narrow it down:
- Assign NULL to all your pointers on initialization
- Use shared_ptr types instead of raw float pointers - these will be automatically cleaned up when no references remain.
I suggest you use an vector or other stl-container, which fits your need.
If it has to be arrays - better use an destructor in your struct, so you need not to think about manually cleanup:
struct foo
{
int a,b,c;
float d;
float *array1;
float *array2;
foo ()
: a(0),
b(0),
c(0),
d(0.0),
array1(NULL),
array2(NULL)
{ }
~foo ()
{
delete [] array1;
delete [] array2;
}
};
edit: removed check of NULL on delete []
This easiest way to accomplish this would be to create a constructor and destructor:
struct foo {
int a,b,c;
float d;
float *array1;
float *array;
foo()
{
array1 = array = 0;
}
~foo()
{
delete [] array1;
delete [] array;
}
};
Even better would be members to track the size of array1 & array so that a copy constructor and/or assignment operator could clone them as needed.
Note: by "easiest" I do not mean "best". :)
You have to add this destructor to your struct foo:
~foo() {
delete []array1;
delete []array2;
}
I suggest also to create a constructor for you foo
that initializes those two pointers to 0:
foo()
:a(0),b(0),c(0),
d(0.0), array1(0), array2(0)
{}
精彩评论