In general when is is it to an allocate an object statically
In general when is is it to an allocate an object statically on the stack (as opposed dynamically on the heap)? Give an example of a programming scenario where an object should certainly be stack allocated. Now the opposite question: in general, when is it better to allocate an object dynamically on the heap (as opposed to the statically on the stack)? Give an example of programming scenario where an object should certainly be heap-allocated.
Solution
Stack:
A stack is a last-in, first-out (LIFO) structure
Example of a programming scenario where an object should certainly be stack-allocated:
void moo()
{
moo();
}
int main()
{
moo();
return 0;
}
In the above example: A stack frame is pushed on the stack every time function foo() is called. Since moo() calls itself infinitely, eventually the stack will run out of memory and cause an overflow.
Heap:
The heap segment keeps track of memory used for dynamic memory allocation.
Example of a programming scenario where an object should certainly be heap-allocated:
int *ptr = new int;// ptr is assigned 4 bytes in the heap
In C++, whenever we use the new operator to allocate memory, this memory is allocated in the application’s heap segment.
