< Previous | Contents | Next >
One problem with allowing a programmer to allocate and free memory is that he might allocate memory and lose any way to get at it, thus losing any way to ever free it. When memory is lost like this, it’s called a memory leak. Given a large enough leak, a program might run out of memory and crash. As a game programmer, it’s your responsibility to avoid memory leaks.
I’ve written two functions in the Heap program that purposely create memory leaks in order to show you what not to do when using dynamic memory. The first function is leak1(), which simply allocates a chunk of memory on the heap for an int value and then ends.
void leak1()
{
int* drip1 = new int(30);
}
302 Chapter 9 n Advanced Classes and Dynamic Memory: Game Lobby
If I were to call this function, memory would be lost forever. (Okay, it would be lost until the program ended.) The problem is that drip1, which is the only connection to the newly acquired chunk of memory on the heap, is a local variable and ceases to exist when the function leak1() ends. So, there’s no way to free the allocated memory. Take a look at Figure 9.4 for a visual representa- tion of how the leak occurs.
Figure 9.4
The memory that stores 30 can no longer be accessed to be freed, so it has leaked out of the system.
To avoid this memory leak, I could do one of two things. I could use delete to free the memory in leak1(), or I could return a copy of the pointer drip1. If I choose the second option, I have to make sure to free this memory in some other part of the program.
The second function that creates a memory leak is leak2().
void leak2()
{
int* drip2 = new int(50); drip2 = new int(100); delete drip2;
}
This memory leak is a little more subtle, but there is still a leak. The first line in the function body, int* drip2 = new int(50);, allocates a new piece of memory on the heap, assigns 50 to it, and has drip2 point to that piece memory. So far, so good. The second line, drip2 = new int(100);, points drip2 to a new piece of memory on the heap, which stores the 100. The problem is that the memory on the heap that stores 50 now has nothing pointing to it, so there is no way for the program to free that memory. As a result, that piece of memory has essentially leaked out of the system. Check out Figure 9.5 for a visual representation of how the leak occurs.
The last statement of the function, delete drip2;, frees the memory that stores
100, so this won’t be the source of another memory leak. But remember, the
Working with Data Members and the Heap 303
Figure 9.5
By changing drip2 so that it points to the memory that stores 100, the memory that stores 50 is no longer accessible and has leaked out of the system.
memory on the heap that stores 50 has still leaked out of the system. Also, I don’t worry about drip2, which technically has become a dangling pointer, because it will cease to exist when the function ends.