Misc Questions and Answers from Students
on Various Topics in CS

Dynamic Memory Allocation

A student writes:

Hey Professor Conrad, I am having trouble understanding dynamic memory allocation as well as the heap. Do you have a good analogy to describe each?

Thank you

My reply:

If you run out of room in your house to store things, you might rent a locker in a "self storage business". This us especially true if you only need the extra space temporarily, or if you can't afford to add an extra story to your house. Or, if you are moving from one apt to another, but need a place to keep stuff in the meantime, you might rent a locker at a self-storage business.

Think of the heap as a great big building full of storage lockers. Everytime you call "new" you are renting a new locker. Everytime you call delete, you are letting the owner know you are finished with that locker. (delete is an unfortunate name... nothing is actually being deleted... It is just being "returned".)

The lockers are variables where you can store values. The pointer returned by "new" us like the key to the locker. When you call delete, you are returning the key.

I hope this helps.

The studnet replies:

Ohhhh, gotcha
Thanks again