How to create the condition of stack overflow in GNU/linux?
-
See: http://stackoverflow.com/questions/294050/how-does-a-stack-overflow – Can Berk Güder Dec 25 '08 at 17:01
-
This is very nearly a dupe of http://stackoverflow.com/questions/62188/stack-overflow-code-golf-closed – Adam Rosenfield Dec 25 '08 at 17:15
8 Answers
a recursive function with no way out should do the trick
pseudo-code, my c is a bit rusty
void stack_overflow()
{
stack_overflow();
}

- 15,915
- 3
- 48
- 72
-
An optimizing compiler will "optimize" this into an infinite loop. – Adam Rosenfield Dec 25 '08 at 17:09
-
4writing code and declaring it to be pseudo-code, just so you don't have to test it, nice. :) – Georg Schölly Dec 25 '08 at 21:12
I'd recommend reading the phrack magazine article "Smashing the stack for fun and profit". It also contains sample code.

- 743
- 4
- 13
You just need to think about what uses the stack in C.
- Dynamic memory allocation (with
malloc()
) uses the heap; - Local variables and function call stacks use the stack.
So, all you have to do is exhaust the stack. Either endless recursion on a function or large local variable creation (don't let them be cleaned up though by going out of scope) should do it.

- 616,129
- 168
- 910
- 942
There are code samples in the Wikipedia article. Why you'd want to cause one is beyond me...

- 176,543
- 40
- 303
- 368
Lot of examples have been referred here in other answers. But every one seems to have missed this.
To force the stack overflow, one needs to understand what is the size of your stack. In linux the default size of the stack is 8MB.
ulimit -a //would give you the default stack size
ulimit -s 16384 // sets the stack size to 16M bytes
So you can force the stack overflow even with an array of say 100 integers , if you tweak the stack size to be that much small.

- 3,263
- 4
- 32
- 48
-
If you double the array size on each iteration and you actually access the last (or first) array element, you'll hit stack overflow in less than 64 iterations on modern computers regardless of the stack size. – Alexey Frunze Jul 04 '12 at 22:49
-
@ AlexeyFrunze : the stack size is not the variant here. there can be million ways to overflow the stack once we know the stack limit. may it be doubling the array size , having an infinitely recursive function call or anything else. – Jay D Jul 04 '12 at 23:14
The simplest way is just declare a large enough automatic stack variable. No recursion or alloca needed. Interestingly, this is not a compile-time error. The size needed will vary by platform:
#define SIZE 10000000
int main(int argc, char **argv)
{
char a[SIZE];
}

- 278,309
- 50
- 514
- 539
"how to create the condition of stack overflow in linux"
The same way you'd create a stack overflow on Windows.
Jason's answer might work, but some compilers by optimize it into a loop. I think adding a a parameter will do the trick:
int Add(int num)
{
num += Add(num);
return num;
}

- 12,963
- 13
- 59
- 78