I recently came across the types of memory allocated to a program - Stack and Heap. But how do we know, what is the best use-case of them. What is better to use stack or heap if i have options available to me, and how do i know them while programming? I read through many articles looking for the solution, but could not find a satisfactory answer.
Asked
Active
Viewed 61 times
0
-
A simple Internet search yields some excellent articles on this topic. https://techdifferences.com/difference-between-stack-and-heap.html (Although I'm not sure why the author thinks implementation of a stack is "hard" and "heap" is easy - just the opposite). – selbie Jan 29 '20 at 06:00
-
Yes, i have done my research and am aware of the differences between stack and heap. I am more focused on the use-cases and situations in where they are useful individually. And how do i know, when and which is more viable while programming? – muditrustagii Jan 29 '20 at 06:02
-
If you are writing in Java, when do you have a choice? But the question is also tagged C++. Why the two different language tags? – kaya3 Jan 29 '20 at 06:06
-
4Pick **a** language. – WhozCraig Jan 29 '20 at 06:07
-
@kaya3, I guess, C++ would suffice for the question. – muditrustagii Jan 29 '20 at 06:08
-
1Use stack memory when the memory requirement is fixed, so it can’t be changed at the time of program is executing. If the requirement is dynamic and size needs to be changed as per the requirement in run time use heap memory. – RajeshDA Jan 29 '20 at 06:12
-
2As a general rule I would always use stack memory. Until you can't. – Galik Jan 29 '20 at 06:18
-
@Galik But since the heap memory is more efficient, who not use it all the time. Until you can't. – muditrustagii Jan 29 '20 at 06:23
-
3@muditrustagi Heap memory is not more efficient. It is very much slower to allocate and deallocate. – Galik Jan 29 '20 at 06:23
-
1Generally, use stack memory as often as you can - there's trivial allocation performance overhead (as compared to `malloc`/`new`, which does a fair-bit of work), memory management is essentially automatic (no need to `free`/`delete`), and you can even do arbitrary sized stack allocations using facilities like `alloca`. Use heap memory if an object needs to exist outside of the block where it's allocated. – radical7 Jan 29 '20 at 06:27