< previous page page_145 next page >

Page 145
The return value from new is a memory address. It must be assigned to a pointer. To create an unsigned short on the free store, you might write
unsigned short int * pPointer;
pPointer = new unsigned short int;
You can, of course, initialize the pointer at its creation with
unsigned short int * pPointer = new unsigned short int;
In either case, pPointer now points to an unsigned short int on the free store. You can use this like any other pointer to a variable and assign a value into that area of memory 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 pPointer points.
If new cannot create memory on the free storememory is, after all, a limited resourceit throws an exception. Some older compilers return the null pointer. If you have an older compiler, check your pointer for null each time you request new memory; but all modern compilers can be counted on to throw an exception.
delete
When you are finished with your area of memory, you must call delete on the pointer. delete returns the memory to the free store. Remember that the pointer itselfas opposed to the memory to which it pointsis a local variable. When the function in which it is declared returns, that pointer goes out of scope and is lost. The memory allocated with the new operator is not freed automatically, however. That memory becomes unavailablea situation called a memory leak. It's called a memory leak because that memory can't be recovered until the program ends. It is as though the memory has leaked out of your computer.
To restore the memory to the free store, you use the keyword delete. For example:
delete pPointer;
When you delete the pointer, what you are really doing is freeing up the memory whose address is stored in the pointer. You are saying, Return to the free store the memory that this pointer points to. The pointer is still a pointer, and it can be reassigned. Listing 9.4 demonstrates allocating a variable on the heap, using that variable, and deleting it.

 
< previous page page_145 next page >

If you like this book, buy it!