Skip to main content
gamedev.net
🔒 Locked

Memory Question

Started by mattfulford Feb 4, 2004 at 12:04 PM 3 replies 350+ views
Original Post
mattfulford
mattfulford
My app contains a pointer to a large terrain object, which contains two quite large 2D arrays (heights and normals). I use the Delete[] command in the Terrain''s destructor to get rid of these arrays but my system still runs out of memory after about four runs of the program. Do I need to be doing something else somewhere (like free(), release(), nulling pointers etc.)? Thanks
Enigma
Enigma
Depends what you mean by 2D arrays. If you mean:
type** array = new type*[sizeX];
for (int index = 0; index < sizeX; ++index)
{
array[index] = new type[sizeY];
}

Then you'll need to do:
for (int index = 0; index < sizeX; ++index)
{
delete[] array[index];
}
delete[] array;

in your destructor.

Otherwise, as long as you delete everything you new you shouldn't be leaking memory. You are deleting the large terrain object aren't you?

Enigma
EDIT: typo

[edited by - Enigma on February 4, 2004 1:13:44 PM]
Crispy
Crispy
You should NULL your pointers if they are ever reused, and always upon initialization (before the first time they are used) - this will guarantee that you won''t be trying to do something like this:

int* n;

if(!n) { ... } //potential crash (depending on the compiler) as n = garbage

A cosmetic note: delete is, as is delete[], new or new[], an operator (just like your favorite *, /, +, -, %, etc.).

Other than that, Enigma''s way of freeing a dynamic array of pointers is the correct one and always the safest one.




"Finishing in second place, simply means you are the first loser." - PouyaCat

"Literally, it means that Bob is everything you can think of, but not dead; i.e., Bob is a purple-spotted, yellow-striped bumblebee/dragon/pterodactyl hybrid with a voracious addiction to Twix candy bars, but not dead."- kSquared
Tree Penguin
Tree Penguin
Wow, that helped me out ! I got an access violation error and this solved it, thanks !
Enigma
Enigma
Actually in C++ I''d argue against nulling pointers immediately after declaration on the grounds that generally you shouldn''t be declaring the pointer before you need it, so it shouldn''t need to be nulled, i.e.:
type* x;
// stuff
x = functionCall();

would be better as:
type* x;
x = null;
// stuff
x = functionCall();

but would be best as:
// stuff
type* x = functionCall();


Enigma

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.