I use this code snippet:
// stackoverflow.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char** argv)
{
int i;
int a[10];
// init
a[-1] = -1;
a[11] = 11;
printf(" a[-1]= = %d, a[11] = %d\n", a[-1], a[11]);
printf("I am finished.\n");
return a[-1];
}
The compiler is GCC for linux x86. It works well without any run-time error. I also test this code in Valgrind, which don't trigger any memory error either.
$ gcc -O0 -g -o stack_overflow stack_overflow.c
$ ./stack_overflow
a[-1]= = -1, a[11] = 11
I am finished.
$ valgrind ./stack_overflow
==3705== Memcheck, a memory error detector
==3705== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==3705== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==3705== Command: ./stack_overflow
==3705==
a[-1]= = -1, a[11] = 11
I am finished.
==3705==
==3705== HEAP SUMMARY:
==3705== in use at exit: 0 bytes in 0 blocks
==3705== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==3705==
==3705== All heap blocks were freed -- no leaks are possible
==3705==
==3705== For counts of detected and suppressed errors, rerun with: -v
==3705== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
From my understanding, heap and stack is the same kind of memory. The only difference is that they grow in the opposite direction.
So my question is:
Why heap overflow/underflow will trigger an rum-time error, while stack overflow/underflow will not?
why C language designer didn't take this into account just like heap, other than leave it Undefined Behaviour
EDIT
Here's an interesting tuto:
http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html
BTW Clang (OSX) detects it, but it's just and extra feature, good old gcc would let you do it.
Old
Would trigger a Segmentation fault (but here it's only one byte it's just overriding the value of another variable, most likely), if you want a stack overflow try something that does an infinite recursion.
Also if you want to make your code segfault proof (for malloc only) I suggest you compile it with electric fence for your tests. It will prevent your program to go above its allocated memory (starting from the first byte)
http://linux.die.net/man/3/efence
As suggested in the comments Valgrind is also a useful tool.
http://valgrind.org/