[try Beta version]
Not logged in

 
Probably simple question about freeing dynamic variables

Mar 13, 2012 at 12:37am
Hi,

I have a struct...

1
2
3
4
5
6
7
8
9
10
struct Vertex
{
	short v[2];
};

struct VertexInfo
{
	Vertex* vertex;
	int _vertexCount;
};

I create an instance of Vertex info within a function and save the pointer in a global(batch).

VertexInfo* batch = new VertexInfo;

Now here is my question...

When I allocate a dynamic array in batch->vertex and at a later point delete batch, does that mean that the array(within batch) 'vertex' is freed also(since its a child of batch)?

Or do I have to delete vertex first, then delete batch?

Many thanks for any advice,


Softy.
Last edited on Mar 13, 2012 at 12:56am
Mar 13, 2012 at 1:19am
You have to delete vertex first, then batch. C++ does not handle your deletes so whenever you declare space of the heap, you better delete it somewhere, no matter how deep the allocation is in your structures.
Mar 13, 2012 at 2:11am
So, even though VertexInfo has been put on the heap, I have to iterate any pointers within VertexInfo that have been allocated memory too? I assumed that if a parent on the heap gets deleted, then all child structures would too? I think I may be expecting too much from the heap manager.

Please excuse me for reiterating my question as I am trying to clear it up in my own head.


Softy.
Last edited on Mar 13, 2012 at 2:34am
Mar 13, 2012 at 4:22am
Nah, it's not that easy in C++. There is ZERO garbage cleanup. Every single bit of memory you allocate in the heap needs to be explicitly deleted somewhere.
Mar 13, 2012 at 4:53am
If you're serious about learning C++, stop using 'new' unnecessarily:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <vector>
struct Vertex
{
    short v[2];
};
struct VertexInfo
{
    std::vector<Vertex> vertex;
    VertexInfo(std::size_t initial_size) : vertex(initial_size) {}
};

int main()
{
    VertexInfo batch(10);
} // batch is deleted, and every vertex is deleted as well. 
Last edited on Mar 13, 2012 at 4:54am
Mar 13, 2012 at 11:52am
Very clear now IceThatJaw, thank you. :)

@Cubbi:
I am restricted to dynamic data structures due to a restriction of the problem I am trying to solve with inline c++ using GLBasic.

I must say that I am enjoying learning c++ more than I expected.

Thanks again for all you help guys!


Softy.
Last edited on Mar 13, 2012 at 11:53am
Topic archived. No new replies allowed.