Many students are confused about how to use the new and delete operators to manage dynamically allocated memory, and how to handle pointers to that memory. Here's another way to visualize dynamic memory that you might find helpful. It's too small for a tutorial, so I figured I'd just throw it up as an ordinary post. If you think it's silly, I apologize. In that case please just ignore it.
So here goes:
Let's think of a block of dynamically allocated memory as an balloon inflated with helium, and think of a pointer to this memory as a string clipped to the balloon. And, to keep this silly analogy going a little further, the new operator is the pump that inflates the balloon, and the delete operator is a pin that deflates it. Now, all you nature lovers know that you shouldn't just let a balloon fly away because it will gradually shrink enough so that some bird or fish will try to eat it and choke on it. So, we always want to keep hold of at least one string clipped to each of our balloons until we're finished with it, and when we are finished with it, we have to use delete to deflate it. It's fine to have more than one string clipped to a balloon at any given time, and it's fine to pass the balloon along from one string to another, but there must ALWAYS be at least one string clipped to every balloon until we call delete to deflate it. And we also have to guard against trying to deflate a balloon that's already been deflated, because if you try to stick a pin in an already-flat balloon you're going to stab yourself.
That's pretty much it -- pass the balloon from string to string as much as you want, but make sure there's always at least one string attached to each balloon until it's deflated. Deflate each balloon as soon as you're finished using it. Make sure that EVERY balloon is deflated by the time you get to the end of the program. And keep track of which strings are attached to which balloons so you don't try to deflate any balloon more than once.
As to the strings -- we aren't going to worry about them. So I don't care how many strings I leave lying around. I don't have to delete every string. The only thing the strings have to do with deflating is that I must use some string to pass the balloon to delete. But I only have to delete every balloon. I Know, you're not supposed to leave the ground littered with strings, but tough, I'll just let Mother Nature (the Operating System) worry about that.
(Note: I used new and delete because I'm assuming we're dealing with arrays. If you have dynamically allocated single objects rather than arrays just use new and delete instead.)
Page 1 of 1
1 Replies - 1822 Views - Last Post: 17 March 2012 - 09:23 PM
Replies To: Balloons and dynamic memory allocation
Page 1 of 1