开发者

Basic C++ memory question

a friend of mine declared a new type using

typedef GLfloat vec3_t[3开发者_如何学Python];

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


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.


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;


It will be deleted the same way it's been allocated - one contiguous piece of memory.

See 2D array memory layout


You almost got it right,

vec3_t[num_xyz* num_frames]

is equivalent to

GLfloat[num_xyz* num_frames][3]

Since you allocated with new[], you have to delete with delete[].


I think that the delete is OK, but to reduce confusion I tend to do this:

struct vec3_t{
  GLFloat elems[3];
};

vec3_t* vertices = new vec3_t[num_xyz* num_frames];

Now you can see the type of vertices and:

delete [] vertices;

is obviously correct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜