|
|
|
|
|
|
|
You can think of the free store as a massive section of memory in which thousands of sequentially numbered cubbyholes lie waiting for your data. You can't label these cubbyholes, though, as you can with the stack. You must ask for the address of the cubbyhole that you reserve and then stash that address away in a pointer. |
|
|
|
|
|
|
|
|
One way to think about this is with an analogy: A friend gives you the 800 number for Acme Mail Order. You go home and program your telephone with that number, and then you throw away the piece of paper with the number on it. When you push the button, a telephone rings somewhere, and Acme Mail Order answers. You don't remember the number, and you don't know where the other telephone is located, but the button gives you access to Acme Mail Order. Acme Mail Order is your data on the free store. You don't know where it is, but you know how to get to it. You access it by using its addressin this case, the telephone number. You don't have to know that number; you just have to put it into a pointerthe button. The pointer gives you access to your data without bothering you with the details. |
|
|
|
|
|
|
|
|
The stack is cleaned automatically when a function returns. All the local variables go out of scope, and they are removed from the stack. The free store is not cleaned until your program ends, and it is your responsibility to free any memory that you've reserved when you are done with it. |
|
|
|
|
|
|
|
|
The advantage to the free store is that the memory you reserve remains available until you explicitly free it. If you reserve memory on the free store while in a function, the memory is still available when the function returns. |
|
|
|
|
|
|
|
|
The advantage of accessing memory in this way, rather than using global variables, is that only functions with access to the pointer have access to the data. This provides a tightly controlled interface to that data, and it eliminates the problem of one function changing that data in unexpected and unanticipated ways. |
|
|
|
|
|
|
|
|
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. |
|
|
|
|
|
|
|
|
You allocate memory on the free store in C++ by using the new keyword. new is 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 int allocates 2 bytes in the free store, and newlong allocates 4. |
|
|
|
|
|