Ann Brown
Ann Brown

Reputation: 535

How to overflow the stack without pushing new stack frames?

One obvious way to cause a stack overflow and get Segmentation fault would be to recursively push stack frames on top of each other until it booms. I'm wondering if stack overflow could happen without even pushing new stack frames.

Creating a large enough array could do it too from experience, but any other possible scenarios?

Upvotes: 5

Views: 146

Answers (4)

Reza Toghraee
Reza Toghraee

Reputation: 1663

C99 uses a resizable array, which you could use and keep resizing it to a larger one. However this resizable array is implemented using alloca. Here's a sample code in UNIX env:

#include <stdio.h>
#include <alloca.h>
#include <stdlib.h>
#include <stdbool.h>

int
main()
{
    while (true)
    {
        void *p = alloca(32UL);
        printf("new memory allocated at %p \n", p);
    }
    exit(EXIT_SUCCESS);
}

And your output will look like this

new memory allocated at 0xbf800a60 
new memory allocated at 0xbf800a30 
new memory allocated at 0xbf800a00 
new memory allocated at 0xbf8009d0 
new memory allocated at 0xbf8009a0 
[1]    3977 segmentation fault  ./a.out

alloca is in the malloc family of functions, except that it allocated memory on the stack by adjusting the stack pointer.

Upvotes: 3

ouah
ouah

Reputation: 145829

By declaring and using a array larger than your stack size:

$ ulimit -s
8192
$

then

int main(void)
{
    volatile char bla[8192 * 1024 + 16] = {0};
}

is likely to segfault when executed.

Upvotes: 1

tenfour
tenfour

Reputation: 36896

Fundamentally speaking the "stack" is just some memory, and a stack overflow is when ESP / EBP go out of bounds of this memory.

You can accomplish this in a number of ways:

  1. Create a huge stack-allocated array that's bigger than the size of the remaining stack space: int x[10000000];
  2. Set ESP directly: __asm mov esp, 0x0
  3. Corrupt the stack so when the current function unwinds, ESP/EBP will be set to garbage: int x; memset(&x, 0, 10000000);

And countless other ways...

Upvotes: 1

Michael F
Michael F

Reputation: 40832

Abuse alloca() or _alloca() if you're developing on Windows SDK/VS:

The alloca() function allocates size bytes of space in the stack frame of the caller.

Note _alloca() is now deprecated in favour of _malloca().

Upvotes: 1

Related Questions