0

What's the difference between stack and heap?

27th Sep 2016, 6:36 AM
dejanualex
dejanualex - avatar
2 Réponses
+ 2
Stack: Stored in computer RAM just like the heap. Variables created on the stack will go out of scope and automatically deallocate. Much faster to allocate in comparison to variables on the heap. Implemented with an actual stack data structure. Stores local data, return addresses, used for parameter passing Can have a stack overflow when too much of the stack is used. (mostly from infinite (or too much) recursion, very large allocations) Data created on the stack can be used without pointers. You would use the stack if you know exactly how much data you need to allocate before compile time and it is not too big. Usually has a maximum size already determined when your program starts Heap: Stored in computer RAM just like the stack. In C, variables on the heap must be destroyed manually and never fall out of scope. The data is freed with delete, delete[], or free Slower to allocate in comparison to variables on the stack. Used on demand to allocate a block of data for use by the program. Can have fragmentation when there are a lot of allocations and deallocations In C++ data created on the heap will be pointed to by pointers and allocated with new or malloc Can have allocation failures if too big of a buffer is requested to be allocated. You would use the heap if you don't know exactly how much data you will need at runtime or if you need to allocate a lot of data. Responsible for memory leaks
27th Sep 2016, 11:10 AM
Raphael
Raphael - avatar
0
thanks for the answer
27th Sep 2016, 4:12 PM
dejanualex
dejanualex - avatar