Hello, All!
I am working on some simple graphics and ran into a problem with memory management. My C++ experience is limited, so I was hoping I could get some pointers on good memory management practices.
Here is the problem I am running into...
To describe render-able polygon, I chose to create
polygon class. One of the class members is a dynamic array of vertices.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 | class polygon
{
public:
polygon(int vertCount)
{
numOfVerticies = vertCount;
vertices = new v2[vertCount];
}
~polygon()
{
delete[] vertices;
}
bool isVisible;
int numOfVerticies;
v2 position;
v2 *vertices;
};
|
You can see that I have a destructor that I intend for memory cleanup when the object is "done".
To init an object of class
polygon, I use the following code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 | typedef struct game_state
{
polygon *player;
} game_state;
void InitPlayer(game_state *state)
{
state->player = new polygon(4);
polygon *p = state->player;
p->isVisible = true;
p->vertices[0] = v2(0, 0);
p->vertices[1] = v2(15, 50);
p->vertices[2] = v2(30, 0);
p->vertices[3] = v2(15, 15);
p->position = v2(10, 10);
}
|
As you can see, I use operator
new to allocate memory, which means I would need to perform memory cleanup with
delete. My hope was that when I delete
player object, it would invoke destructor, and delete the memory allocated for
verticies member.
This is what I call at clean up stage
| delete[] gameState->player;
|
This does invoke
polygon destructor indeed, but when it executes the line
exception happens (Exception thrown: read access violation.)
I would appreciate if someone could point out if my understanding of mem clean up is incorrect and what pattern is best to follow.
Happy Holiday, Everyone!