C++ Memory Management

C++ objects and other variables are stored in one of three places. The static area is allocated at compile time, and includes things declared static, along with storage for constants and other odds and ends known before the program starts. Normal variables are allocated on the stack, along with other record-keeping data used when calling functions. When the program starts a function, or enters any curly-braced block, it allocates some space on the stack, which is reclaimed when the block is left. The third storage area, which we haven't used much so far, is called the heap. Space is allocated and returned to the heap by explicit operations in the program. More specifically:

In Java, all objects are allocated on the heap using new, and Java uses a garbage collector to automatically free objects which are no longer in use.

C++ takes a different approach. Objects can be created on the stack, but sometimes you need to create them dynamically using new, much as in Java. C++ does not provide a generalized garbage collection service. As the cliche goes, it's complicated.

The C++ designers judge that memory management is not suited to a one-size-fits-all solution. The programmer should solve it in the best way for the problem at hand, and C++ provides several tools for this purpose. This is not complete insanity. General garbage collection is very expensive, and can cause great variation in the running times of a program's operations. This is a problem for real-time systems, which need predictable run-times.

On the other hand, the C++ approach is more trouble for the programmer, and introduces all sorts of pitfalls that simply don't exist in Java. But it follows from the differences in design philosophies. (In the case of C++, the first three design goals are “Run fast,” “Run really fast,” and “Don't do anything to slow down the program.”) Though C++ makes memory management the programmer's responsibility, it does provide some tools to do the job. Of particular interest:

One note about the term heap. Don't confuse it with the data structure. Our “heap” refers to a a region of memory, having no specific layout. The name is probably chosen to contrast with the more ordered “stack.”

The null pointer value should be written nullptr since C++11. The constant zero will also work, since it automatically converts to null pointer. In plain C, the name NULL is often used, and you will frequently see this in C++. The null pointer converts automatically to boolean, so for pointer p, if(p) ... is equivalent to if(p == nullptr) ....

This section discusses memory management features available only in C++. The last subsection summarizes memory management in plain C.

Textbook: The last part of Ch. 17, pp. 652—674, discusses dynamic allocation. The text does not discuss smart pointers, however.