|
|
|
|
|
|
|
out of space available for dynamic data, the new operator returns the null pointer. |
|
|
|
|
|
|
|
|
Variables created by new are said to be on the free store (or heap), a region of memory set aside for dynamic variables. The new operator obtains a chunk of memory from the free store and, as we will see, the delete operator returns it to the free store. |
|
|
|
 |
|
 |
|
|
Free Store (Heap) A pool of memory locations reserved for allocation and deallocation of dynamic data. |
|
|
|
|
|
|
|
|
A dynamic variable is unnamed and cannot be directly addressed. It must be indirectly addressed through the pointer returned by the new operator. Below is an example of creating dynamic data and then accessing the data through pointers. The code begins by initializing the pointer variables in their declarations. |
|
|
|
|
|
|
|
|
#include <string.h> // For strcpy()
.
.
.
int* intPtr = new int;
char* nameStr = new char[6];
*intPtr = 357;
strcpy(nameStr, Ben); |
|
|
|
|
|
|
|
|
Recall from Chapter 12 that the strcpy library function requires two parameters, each being the base address of a char array. For the first parameter, we are passing the base address of the dynamic array on the free store. For the second parameter, the compiler passes the base address of the anonymous array where the string Ben (including the terminating null character) is located. Figures 17-6a and 17-6b picture the effect of executing this code segment. |
|
|
|
|
|
|
|
|
Dynamic data can be destroyed at any time during the execution of a program when it is no longer needed. The built-in operator delete is used to destroy a dynamic variable. The delete operation has two forms, one for deleting a single variable, the other for deleting an array: |
|
|
|
|
|