Stack vs Heap

Hey everybody
I was wondering when to use heap based allocations vs stack based ones. Even though ive been programing for about a year or two ive still never used anything thats heap based. I dont know if i just havent had any legit uses for it or im just too n00b
You really ought to use the heap where possible and only hold simple/small objects on the stack.

Although many modern OS' can grow the stack dynamically, it is a very finite resource. The heap is the general purpose pool of memory. It gets larger as more physical memory is added to the machine.

The default stack on MS-DOS with Microsoft/Lattice C was 2K. Many modern embedded environments aren't much larger, at any rate they certainly don't grow.
So i should mostly use the heap for large objects?
You should only use the heap for large objects.
The stack has much less available memory than the heap. This is mostly a problem if you allocate huge (multidimensional) arrays, or have deep or infinite recursive functions.

Another thing is that allocations on the stack must have a fixed size known at compile time and it is destroyed when it goes out of scope. With heap allocated objects there is much more freedom to decide when an object should be destroyed. This makes the stack unstable for collection of things where you can add and remove elements. std::vector, std::string, std::list, etc. all use heap allocations internally.
Last edited on
Ok, i see. Thank you guys
Topic archived. No new replies allowed.