Home > Back-end >  Motivation for the heap lifecycle to be different from the stack lifecycle
Motivation for the heap lifecycle to be different from the stack lifecycle

Time:08-16

Working with C , I have to ask some language semantics about the stack vs the heap. Firstly when we create an object on the stack it's very clear how long its life cycle is. Once it exits the {} scope operator then it is handled by the compiler and destroyed. This is fine.

When we create an object on the heap using the new keyword, the motivation being the object itself is too large to be placed on the stack. Why then do we then have different lifecycle semantics for the heap object. Suddenly the heap object has a lifecycle of the program rather than the local scope.

Now ignoring that smart pointers handle the concept of ownership for these heap objects in much the same way as stack objects. That being when the smart pointer falls out of scope so does the object its pointing to.

What I'm asking is what/why is the motivation to give heap objects a different lifecycle than stack objects.

CodePudding user response:

It has nothing to do with size.

The sole purpose of heap objects is that they have a different lifecycle than stack objects. With the heap you can dynamically create and destroy objects at runtime, whenever you feel like it. You could pass an object on the heap from one block to another and transfer ownership to that different block, where with a stack object you would be bound to the lifetime of the block.

CodePudding user response:

Imagine very simple function which allocated the memory for the int array and sets the random values to its elements.

int *createArray(size_t size)
{
    int *x = malloc(sizeof(*x) * size);
    if(x)
        for(size_t index = 0; index < size; index  ) x[index] = rand();
    return x;
}

The caller can use this array as its lifetime is not limited to the function scope.

If I modify it to use automatic storage duration array, if the caller tries to use the returned reference, it will invoke UB as the array is accessed outside the function scope:

int *createArray(size_t size)
{
    int x[size];
    for(size_t index = 0; index < size; index  ) x[index] = rand();
    return x;
}
  • Related