4

I understand that if you have a multithreaded application, and you need to allocate a lot of memory, then you should allocate on heap. Stack space is divided up amongst threads of your application, thus the size of stack for each thread gets smaller as you create new threads. Thus, if you tried to allocate lots of memory on stack, it could overflow. But, assuming that you have a single-threaded application, is the stack size essentially the same as that for heap?

I read elsewhere that stack and heap don't have a clearly defined boundary in the address space, rather that they grow into each other.

P.S. Lifetime of the objects being allocated is not an issue. The objects gets created first thing in the program, and gets cleaned at exit. I don't have to worry about it going out of scope, and thus getting cleaned from stack space.

trincot
  • 317,000
  • 35
  • 244
  • 286
The Vivandiere
  • 3,059
  • 3
  • 28
  • 50

1 Answers1

2

No, stack size is not the same as heap. Stack objects get pushed/popped in a LIFO manner, and used for things such as program flow. For example, arguments are "pushed" into the stack before a function call, then "popped" into function arguments to be accessed. Recursion therefore, uses a lot of stack space if you go too deep. Heap is really for pointers and allocated memory. In the real world, the stack is like the gears in your clock, and the heap is like your desk. Your clock sits on your desk, because it takes up room - but you use it for something completely different than your desk.

Check out this question on Stack Overflow:

Why is memory split up into stack and heap?'

Community
  • 1
  • 1
Dan Chase
  • 993
  • 7
  • 18