OS X Stack Size

FoolyCooly

Registered
I have been wrestling with this problem longer than I realized. Programs that work fine while working with smaller values, often crash while working with larger values. I always thought this was some flaw in my code until a proffesor began talking about linux and windows stack sizes. Apparently, both windows and the mac have comparitively low stack sizes when juxtaposed with linux.

My current program deals with an array of <1048576> integers, int array[1048576], and it gives me a segmentation fault in both PB and in Terminal, but is perfectly happy on my school's linux server. The array initializes, but always crashes after x number of operations working with the array.

I've tried using the # (stacksize) command with g++ but that doesn't really seem to work on the above array. I was curious if anyone else has experienced this and learned a good workaround aside from re-coding everything.

Thanks, sincerely, for any help :)
 
The default stack size is 512k on OS X. You're trying to allocate four megabytes on the stack. Try allocating your array on the heap as such:


Code:
int * array = malloc(sizeof(int) * 1048576);

//important stuff goes here

free(array);
 
You should probably take the good advise from anarchie and allocate your data on the heap.

The stack size is an OS thing and can't be set by the compiler.

You _could_ set the stacksize from the shell with something like "limit stacksize 4000000", but this can only be done by a super user and it's only valid for that session.

I don't recommend developing and testing code as a super user though.
 
For whatever reason it blanked my mind, but as soon you mentioned the heap I remembered the window's workaround for it, and thats simply to delcare the array, in any form, outside the main() function, like a global variable.

I apologize for this late reply but I would still like to say that I am sincerely greatful for your help.

:)
 
If you declare a global char[1024768] in your code, you'll end up tacking an extra megabyte onto your application size. Sure, it'll compress well, but that's about it.
 
Originally posted by gumse

You _could_ set the stacksize from the shell with something like "limit stacksize 4000000", but this can only be done by a super user and it's only valid for that session.

That is not 100% correct. There are hard limits and soft limits and any user can set the soft limit to whatever they want. I believe that by default the stacksize limit is a soft one so you can change it at will. That said a small stack size is generally a good thing since it catches infinite recursions much faster and in addition since each thread needs its own stack using large stacks can waste lots of your address space.

-Eric
 
Back
Top