Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic C++ memory question

Tags:

c++

opengl

a friend of mine declared a new type using

typedef GLfloat vec3_t[3];

and later used vec3_t to allocate memory

vertices=new vec3_t[num_xyz* num_frames];

He freed the memory using

delete [] vertices;

Question:
1. Since vec3_t is an alias for GLfloat[3], does it mean that

vec3_t[num_xyz* num_frames] 

is equivalent to

GLfloat[3][num_xyz* num_frames];  

2. If the above is a 2 dimentional array, How is it supporsed to be properly deleted from memory?

thanks in advance;
from deo

like image 468
Dr Deo Avatar asked Jan 04 '10 08:01

Dr Deo


2 Answers

1. a two dimensional array can be thoght of as a one dimensional array where each element is an array.
using this definition you can see that new vec3_t[num_xyz* num_frames] is equivalent to a two dimensional array.

2. this array is made of num_xyz* num_frames members each taking a space of sizeof (vec3_t)
when new is carried out it allocates num_xyz* num_frames memory blokes in the heap, it takes note of this number so that when calling delete[] it will know how many blocks of sizeof (vec3_t) it should mark as free in the heap.

like image 150
Alon Avatar answered Sep 21 '22 05:09

Alon


GLfloat is an array that is "statically" allocated and thus that doesn't need to be explicitly deallocated.

From a memory point of view, this typedef is equivalent to the following structure:

typedef struct {
  GLfloat f1;
  GLfloat f2;
  GLfloat f3;
} vec3_t;

You can then have the following code which is now less confusing:

vec3_t* vertices = new vec3_t [num_xyz* num_frames];
[...]
delete[] vertices;
like image 33
cedrou Avatar answered Sep 22 '22 05:09

cedrou