In: Computer Science
b) 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 a programming scenario where an object should certainly be heap-allocated.
Generally, the objects are stored dynamically in Heap. That gives them the flexibilty of unlimited storage as opposed to the confined storage of an object stored in the stack statically. Not just the storage advantage, the objects stored in the Heap area are not automatically de-allocated and they are accesible at any point of time.We cannot have the knowledge that where in the heap area the particular object is placed Literally, it lives untill we explicitly de-allocate it. It lives untill the end of the function-call. In java these are cleared by Daemon Threads.So the life time of the object is also not fixed. The memory allocation is done at the run time.
If suppose a object in heap area is intialised with a value, the value of the onject remains unchanged through out the execution of code untill the program uses it. In such scenarios the heap allocations can be implemented.
Heap is used when the amount of memory needed by the object for allocation at the run time is unknown.
Let us consider a program that stores infomation of students. The list of students cannot be confined, because there are always entries and deletions. And the duration of the student that stays in the college is unkown. in such cases this can be employed.