память – Why do you need a heap at all?

Question:

I've read a lot of posts on memory organization, but I still don't understand why a heap is needed at all? Why isn't some global stack or something like that used instead?

Answer:

Think of the heap as a structure from which you can ask for a piece of memory at any time , and to which you can return this memory at any time .

You can't do that with a stack: you can only return an object back after all the previous objects have returned.

For example, in a hypothetical language that only has a stack, this would be:

object* function()
{
    aux_object* ao = new aux_object();
    object* o = new object();
    o -> copySettingsFrom(ao);
    delete ao;
    return o;
}

would be impossible, because ao could not be freed before o was freed!

Scroll to Top