> On Mar 3, 2015, at 12:21 PM, Patrick Collins <[email protected]> 
> wrote:
> 
> Right... But I guess what's not clear to me is, when does one use malloc over 
> the stack version?  Is it only when you have a stack overflow?  Or is there 
> some magic number of elements that fall under a best-practice-use-malloc rule?

If the array has to outlive the function that created it, then clearly you have 
to use malloc (or a passed-in buffer.)

If it’s purely temporary to the function, then you have a choice. It’s not a 
clear-cut choice because it’s not easy to predict how much stack space you 
have. It varies by OS and even by version. On OS X the main thread gets a 
goodly amount (I’m vaguely remembering 32MB?) while background threads by 
default get much less. I don’t know whether iOS differs. Also, of course, some 
amount of stack will already have been used up by the time your function is 
called. And if your function could recurse, then of course things get much 
scarier.

My rule of thumb is that I’ll allocate “a few kbytes” on the stack, otherwise I 
go to malloc. These days maybe 16k? But I tend to write libraries that can get 
used in lots of places in different people’s apps. If you own the app and know 
that function will run on the main thread without a deep call stack, you can 
safely put megabytes on the stack.

Another useful thing to know is that nowadays C allows variable-size arrays in 
local variables. So this is legal (and convenient):
        unsigned n = …some computation…;
        float myArray[n];

—Jens

PS: OT, but one of the things I like about the Go language <http://golang.org 
<http://golang.org/>> is that it uses growable stacks, so you never have to 
worry about running out of stack space. And as a side benefit, it creates 
threads with tiny stacks (2kbytes!) which makes threads insanely cheap.
 _______________________________________________
Do not post admin requests to the list. They will be ignored.
Objc-language mailing list      ([email protected])
Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/objc-language/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to