+ 3

Can anyone give example of a real world problem where programmer should use heap instead of stack?

Using heap in c++

19th Dec 2016, 8:32 AM
Doni
Doni - avatar
4 Respuestas
+ 6
stack memory is allocated at compilation time int x[100]; // allocated at compilation time while heap memory is allocated at runtime (remember to free it afterwards!!!) int *y; y = new int[100]; // allocated at runtime delete y; // frees the allocated memory imagine you have an array which grows all the time, hence, you do not know what the size it will eventually turn out to be. in that case you should use dynamic allocation (heap memory) if you have constant table of something that does not change during the execution, use static allocation (stack memory)
19th Dec 2016, 8:58 AM
Burey
Burey - avatar
+ 3
eventually you are limited by the specs of your computer but unless you start allocating by the hundred of thousands you do not need to worry
19th Dec 2016, 9:05 AM
Burey
Burey - avatar
+ 1
One answer is to avoid the memory constraints imposed by the stack, but really the answer is to use it for any object you want to live longer than your current scope. For instance, if I apawn an entiry on a game, I want it to last a while and not just for the duration of the function I called it in. Another case would be when I want to allocate a variable number of objects. The stack needs to be very deterministic aboit how it runs. Therefore, the program needs to know at compile time how much memory each layer of scope is going to be allocated. This is why you must supply a constant when declaring a normal array, for instance. The heap has no such restrictions and so you can dynamically allocate space to the exact amount you need at any given time. Sure you can allocate an excessive amount on the stack, but this would be wasted space. Additionally, if you were to exceed that limit your program will likely not behave as expected.
21st Dec 2016, 9:20 AM
Thomas Stone
Thomas Stone - avatar
0
So there would be maximum limit of stack and heap memory available for a program that makes this necessary?
19th Dec 2016, 9:01 AM
Doni
Doni - avatar