[haiku] Re: Heap vs Stack

  • From: "Ingo Weinhold" <ingo_weinhold@xxxxxx>
  • To: haiku@xxxxxxxxxxxxx
  • Date: Thu, 09 Aug 2012 22:05:23 +0200

Scott Kemp wrote:
> I'm sure this is a simple question for most - but when should a programmer
> store information in the heap versus the stack. Am I right to assume that
> normally a local variable could be stored in the stack and a global
> variable or maybe an array would be better in the heap?

Unless the compiler places them in registers local variables are always 
allocated on the stack. And rather importantly, local variables only live until 
the scope they are defined in is left. So this is the main restriction of stack 
usage: If you want your allocation to continue to live after your function 
returns, you can't allocate it on the stack (note that this doesn't mean 
objects that are returned by value and thus copied).

So generally, if your function needs to make a temporary allocation, the stack 
is fine, unless the size of the allocation is problematic. If you use too much 
stack, you're program will crash. As a rule of thumb, up to a few KiB of stack 
space allocated in a function is usually OK, unless you deeply nest functions 
doing that (e.g. a recursive function). When in doubt use the heap.

> Also I'm reading that the stack has a smaller, limited capacity. How large
> is the stack normally, does it vary by OS or environment?

Yes, the stack is limited and varies by OS and possibly even thread type. E.g. 
in Haiku a program's main thread can use up to 16 MiB of stack, other threads 
up to 256 KiB.

> Can I check for free heap and stack memory?

Not that I know of.

BTW, the haiku-3rdparty-dev mailing list [1] is more suitable for these kinds 
of questions.

CU, Ingo

[1] //www.freelists.org/list/haiku-3rdparty-dev

Other related posts: