stackoverflow for empty function

Viewed 176

Look at this code :

void f()
{
    f();
}

I know that because so many f() ​​functions are called, StackOverflow occurs. But my question is what is exactly stored in the stack that causes this error, return address for each f() function call? Because this function has no variables, so why does StackOverflow occur?

2 Answers

For every function called the stack stores its return address, in order to resume execution at the next instruction when the function returns. This is the call stack.

As the other answers already said, it's because of the return addresses.

void f(){
  f();
}

compiles to

f:
  call f #Let's assume f has the address 0x1000 for later purposes
  ret

But what does call do? It does two things:

  1. Push the current address to the stack
  2. Call the specified address. It's essentially:
f:
  push %rip
  jmp 0x1000
  ret

If you "unroll" this calls you have:

f:
  push %rip
  push %rip
  push %rip
  push %rip
  push %rip
  push %rip
  ....

And so on. As you can see, you always push an address to the stack. This works until you hit other areas and overwrite them. (This illustration assumes an architecture with a backwards-growing stack, like x86)

[heap].......[stack pointer][stack] #Start
[heap]......[stack pointer][stack ] push %rip
[heap].....[stack pointer][stack  ] push %rip
[heap]....[stack pointer][stack   ] push %rip
[heap]...[stack pointer][stack    ] push %rip
[heap]..[stack pointer][stack     ] push %rip
[heap].[stack pointer][stack      ] push %rip
[heap][stack pointer][stack       ] push %rip
[heap[stack pointer][stack        ]# Boom, you for example reached the heap and you are overwriting it.
Related