I have been playing around with the stack on a Ubuntu 9.04 system running gcc 4.3.3 with the randomize_va_space kernel variable set to 0(/proc/sys/kernel/randomize_va_space)
If I declare an auto variable in a function which is an array with its size being determined by the input then how is the array allocated on the stack?
The function looks something like this -
int fun(int i) {
char a[i];
char *ptr;
printf("a - %p ptr - %p\n", a, &ptr);
printf("Difference - %ld\n", ((unsigned long)&ptr - (unsigned long)a);
printf("sizeof(a) - %d\n\n", sizeof(a));
}
The sizeof operator when passed the array a returns the expected size (even -1)so I was wondering why does the array take so much space on the stack, and secondly why is sizeof() returning a -1?
The output looks something like this -
a - 0xbffff4c0 ptr - 0xbffff4fc
Difference - 60
sizeof(a) - -1
a - 0xbffff4c0 ptr - 0xbffff4fc
Difference - 60
sizeof(a) - 0
a - 0xbffff4c0 ptr - 0xbffff4fc
Difference - 60
sizeof(a) - 1
a - 0xbffff4b0 ptr - 0xbffff4fc
Difference - 76
sizeof(a) - 2
a - 0xbffff4b0 ptr - 0xbffff4fc
Difference - 76
sizeof(a) - 3
a - 0xbffff4b0 ptr - 0xbffff4fc
Difference - 76
sizeof(a) - 4