Programs maintain 3 areas of data memory:
|
You can ask for memory from the heap. C++ allocates memory and gives you
back the address of the first byte of the allocated memory. The way to do this
is to use the new
construct. (C++ only. C uses something
different, called malloc
)
int *ip; ip = new int; This can also be combined: int *ip = new int; |
|
Note: ip is now initialized. *ip is not.
The arrows denote the direction of growth of that portion of memory. You'll note that the stack and the heap grow towards each other. They can actually meet if you happen to be particularly unlucky. More about that tomorrow.
Why use dynamic allocation?
The demo pointer2.cpp is taken directly from the book. It shows how you can work with the new construct.
Well, now you've got memory. What do you do with it when you're
done? Same thing you always do when you're done with something you've
borrowed: give it back. The delete
command gives
allocated memory back to the heap. Here's a before and after of a
delete command:
Before |
|
After |
|
See the problem? That leads to the next topic:
Once you give memory back to the heap,
you no longer have the right to do anything with it, even
though you can still access it. So, after you delete ip, saying
cout << *ip;
is an error, but not one that the
compiler will catch. You also are not allowed to delete the memory a
second time.
If you aren't careful, you can lose all pointers to memory from the heap, and you will then have no way to access it or give it back. An example:
int *ip = new int; |
|
ip = new int; |
|
We finish today off with a program demonstrating a couple of the most common mistakes made with pointers, pointerMistakes.cpp. There is one good thing in the program, a typedef.