< Previous | Contents | Next >

Dynamically Allocating Memory

So far, whenever youve declared a variable, C++ has allocated the necessary memory for it. When the function that the variable was created in ended, C++ freed the memory. This memory, which is used for local variables, is called the stack. But theres another kind of memory that persists independent of the functions in a program. You, the programmer, are in charge of allocating and freeing this memory, collectively called the heap (or free store).

At this point, you might be thinking, Why bother with another type of memory? The stack works just fine, thank you.Using the dynamic memory of the heap offers great benefits that can be summed up in one word: efficiency. By using the heap, you can use only the amount of memory you need at any given time. If you have a game with a level that has 100 enemies, you can allocate the memory for the enemies at the beginning of the level and free the memory at the end. The heap also allows you to create an object in one function that you can access even after that function ends (without having to return a copy of the

Dynamically Allocating Memory 297


object). You might create a screen object in one function and return access to it. Youll find that dynamic memory is an important tool in writing any significant game.


 

Introducing the Heap ProgramUsing the new OperatorUsing the delete OperatorAvoiding Memory Leaks