Memory Leaks

Afforess

The White Wizard
Joined
Jul 31, 2007
Messages
12,239
Location
Austin, Texas
As I understand it, in C++, there is no automatic garbage collectors (like Java has), so programmers have to delete arrays when they are done with them. This is done by SAFE_DELETE_ARRAY (In Civ4).

Then, why does bool CvUnit::nuke(int iX, int iY) create an array, but never delete it? Is this causing a memory leak?
 
Wait, Wait... I think I have answered my own question here. The array in CvUnit:nuke(...) is of a fixed size, so it isn't a pointer, but the other one is a pointer, and has to be treated differently.

Am I right?
 
Correct. If you allocate the array using the "new" operator, the memory for it is allocated in the heap, the global pool of memory for the application. If the array is declared with a fixed length without the "new" operator it is allocated on the stack, memory that is freed automatically when the function exits.

Note that the key is not a constant size for the array but rather the use of the "new" operator that determines whether or not you need to use "delete."

Code:
int foo[5];              // automatically freed
int *foo = new int[5];   // must use delete
 
Top Bottom