Why would you ever want to allocate memory on the

2020-01-27 02:54发布

Possible Duplicate:
When is it best to use a Stack instead of a Heap and vice versa?

I've read a few of the other questions regarding the heap vs stack, but they seem to focus more on what the heap/stack do rather than why you would use them.

It seems to me that stack allocation would almost always be preferred since it is quicker (just moving the stack pointer vs looking for free space in the heap), and you don't have to manually free allocated memory when you're done using it. The only reason I can see for using heap allocation is if you wanted to create an object in a function and then use it outside that functions scope, since stack allocated memory is automatically unallocated after returning from the function.

Are there other reasons for using heap allocation instead of stack allocation that I am not aware of?

9条回答
劳资没心,怎么记你
2楼-- · 2020-01-27 03:17

Size limits are a huge dealbreaker in a lot of cases. The stack is usually measured in the low megabytes or even kilobytes (that's for everything on the stack), whereas all modern PCs allow you a few gigabytes of heap. So if you're going to be using a large amount of data, you absolutely need the heap.

查看更多
Lonely孤独者°
3楼-- · 2020-01-27 03:17

just to add you can use alloca to allocate memory on the stack, but again memory on the stack is limited and also the space exists only during the function execution only. that does not mean everything should be allocated on the heap. like all design decisions this is also somewhat difficult, a "judicious" combination of both should be used.

查看更多
The star\"
4楼-- · 2020-01-27 03:18

The stack and heap share the same "open" memory space and will have to eventually come to a point where they meet, if you use the entire segment of memory. Keeping the balance between the space that each of them use will have amortized cost later for allocation and de-allocation of memory a smaller asymptotic value.

查看更多
登录 后发表回答