www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

C++ Tutorial - Lesson 19: Dynamic Memory Allocation

Introduction to Dynamic Memory Allocation

by John Kopp

Support this site at no cost to you

Introduction
Welcome to EasyCPlusPlus.com's free tutorial on C++ programming. This lesson is a brief aside in our tour of classes and objects, but it covers a topic, dynamic memory allocation, that will be needed in future lessons. In C++, space in memory for variables may be either statically or dynamically allocated. Statically allocated objects are those that are not created with the memory allocator new, that is, they are just the ordinary objects we have been using through out this tutorial.

int x;
float money;
Employee janitor;

These objects are of fixed, known size and the compiler arranges the required space as it turns source code into a binary or executable program. Statically allocated objects that are of local scope are put into a memory space known as the stack. Statically allocated objects of global scope live in the global address space. The key point is that for these objects their size is fixed at compile time.

Now, suppose we don't know the size of an object until program execution. Examples of this are a buffer to hold a block of text of variable size, or an array with an undetermined number of elements We could try to size the buffer or array to be large enough to hold the worst case, that is, to be big enough to hold anything we should encounter. But, there are two problems with this strategy. First, it consumes memory unnecessarily. This is less of an issue than in the past when memory was more limited, but still impacts overall system performance. Second, no matter how much memory is statically set aside for our object, we can never be sure it will be large enough. This is really a ticking time bomb. Eventually, someone will try to load one too many elements, or type on too many words and then our program will either crash or run erratically. The solution to this problem is dynamic memory allocation, which is not surprising given the title of this lesson.

Previous Page       Next Page