Why did my application crash when recursive too many

I think anyone who works as Software Engineer is faced with app crash problems when recursive too many times. In this article, I will explain why applications to crash when recursive too many times at technical vision.

Let’s start

1. Stack frame

A stack frame is a memory unit of a stack. It contains data when you called a function. Each function call will create a stack frame and when the function call run is done, the stack frame will be dealloc.

2. What does the stack frame contain?

Before the function call, The caller will send parameters of the callee function into a new stack frame. The callee function also declares local variables in it.

So, the stack frame will contain:

  • Parameters pass from caller function.
  • Local variable

3. Tại sao stack bị tràn

Stack là một vùng nhớ rất nhỏ, nó không lớn như heap. Nó chỉ được dùng để lưu trữ các giá trị trong lúc function call. Thế nên nó rất dễ bị tràn (sử dụng hết) trong quá trình chương trình chạy nếu gọi hàm đệ quy quá nhiều lần.

4. Why does my application still crashes when my function doesn’t have any parameter or local variables

We try to run an example program below:

#include <stdio.h>

void exe() {
    exe();
}

int main() {
    exe();
    return 0;
}

As I mentioned above, the stack frame contains parameters and local variables. However, It needs a space to store rbp register (used to determine the bottom of the current stack frame). And, in some CPU architects, stackframe also contains return value.

So each time call exe function. The programming still creates a new stackframe and push rbp into it. Then stack still grows and the program still crashes whether the function has variable or not.

5. Learn more

Leave a Reply