Re: [OT] Dynamic Stack Allocation
On Monday, Jul 28, 2003, at 23:58 US/Eastern, Sam Vaughan wrote: This is a little off-topic, but perhaps of interest to the curious... I was amazed to find this (summarised) code in the Darwin DiskArbitration source (FSParticular.c line 352): void foo() { int j = bar(); CFDictionaryRef dicts[j]; CFStringRef keys[j]; } It is part of C99 and also a GCC extension which is turned on by default. To my surprise, this compiles with no warnings and works. I would have expected a compiler error since it doesn't know at compile time how large to make the two arrays. I then wrote a test app called foo.c: #include <stdio.h> int main(int argc, char** argv) { if (argc < 2) return 0; int items = atoi(argv[1]); int fred[items]; printf("allocated fred[%d], items in fred: %d\n", items, sizeof(fred) / sizeof(fred[0])); return 0; } And this is what I got: % gcc -o foo foo.c % ./foo 1 allocated fred[1], items in fred: 1 % ./foo 1000 allocated fred[1000], items in fred: 1000 % ./foo 1000000 Segmentation fault The problem is that the default max stack size is only 512K. You can increase it by using limit or ulimit depending on you shell. Looking at the disassembly it appears that the stack is dynamically grown to accommodate the requested memory. Gauging by the dismayed response from others I've shown this to, I'm guessing it's not very portable! Interesting nonetheless. It is as long as you have a C99 compiler or just GCC and have enough stack size. Thanks, Andrew Pinski _______________________________________________ darwin-kernel mailing list | darwin-kernel@lists.apple.com Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/darwin-kernel Do not post admin requests to the list. They will be ignored.
participants (1)
-
Andrew Pinski