[OT] Dynamic Stack Allocation
[OT] Dynamic Stack Allocation
- Subject: [OT] Dynamic Stack Allocation
- From: Sam Vaughan <email@hidden>
- Date: Tue, 29 Jul 2003 13:58:54 +1000
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];
}
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
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.
Sam
_______________________________________________
darwin-kernel mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/darwin-kernel
Do not post admin requests to the list. They will be ignored.