The disadvantage of the free store is also that the memory you reserve remains available
until you explicitly state you are done with it by freeing it. If you neglect to free that
memory, it can build up over time and cause the system to crash.
The advantage of accessing memory in this way, rather than using global variables, is
that only functions with access to the pointer (which has the appropriate address) have
access to the data. This requires the object containing the pointer to the data, or the
pointer itself, to be explicitly passed to any function making changes, thus reducing the
chances that a function can change the data without that change being traceable.
For this to work, you must be able to create a pointer to an area on the free store and to
pass that pointer among functions. The following sections describe how to do this.
Allocating Space with the newKeyword ........................................................
You allocate memory on the free store in C++ by using the newkeyword. newis followed
by the type of the object that you want to allocate, so that the compiler knows how much
memory is required. Therefore,new unsigned short intallocates two bytes in the free
store, and new longallocates four, assuming your system uses a two-byte unsigned
short intand a four-byte long.
The return value from newis a memory address. Because you now know that memory
addresses are stored in pointers, it should be no surprise to you that the return value from
newshould be assigned to a pointer. To create an unsigned shorton the free store, you
might write
unsigned short int * pPointer;
pPointer = new unsigned short int;
You can, of course, do this all on one line by initializing the pointer at the same time you
declare it:
unsigned short int * pPointer = new unsigned short int;
In either case,pPointernow points to an unsigned short inton the free store. You
can use this like any other pointer to a variable and assign a value into that area of mem-
ory by writing
*pPointer = 72;
This means “Put 72 at the value in pPointer,” or “Assign the value 72 to the area on the
free store to which pPointerpoints.”
234 Day 8