Setting the value of an int can cause a segfault

Can the following code cause a segfault?


void fun2()
{
char big[1024* 1024 * 10];
volatile int k=0;
}

int main()
{
fun2();
}


The answer is, yes if the process stack size is smaller then 10Mb.
The trick I've used is to set the "k" variable as volatile, otherwise GCC would optimize the code and place the int at the top of the stack, i.e. within the process' memory boundaries.

If you look at the function preambul GCC has generated for fun2 you can clearly see how the stack is grown by subtracting 0xa00018 from the stack pointer. For a process stack size of 8Mb this is beyond the limit.


(gdb) disassemble fun2
Dump of assembler code for function fun2:
0x00001f92 : push %ebp
0x00001f93 : mov %esp,%ebp
0x00001f95 : sub $0xa00018,%esp
0x00001f9b : movl $0x0,-10485772(%ebp)
0x00001fa5 : leave
0x00001fa6 : ret
End of assembler dump.


Later on, when trying to set the value of k via movl the process is signalled by the kernel.

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0xbf5ffb0c
fun2 () at teststack.c:4
4 volatile int k=0;
(gdb) whe
#0 fun2 () at teststack.c:4
#1 0x00001fb2 in main () at teststack.c:9


There, even setting an integer's value can cause a segfault.