Programming/Java

StackOverflowError가 뭘까? (사이트 아님)

이진2 2021. 11. 8. 22:22

https://stackoverflow.com/questions/3197708/what-causes-a-java-lang-stackoverflowerror/3197731

 

What causes a java.lang.StackOverflowError

What can cause a java.lang.StackOverflowError? The stack printout that I get is not very deep at all (only 5 methods).

stackoverflow.com

When a function call is invoked by a Java Application, a stack frame is allocated on the call stack. The stack frame contains the parameters of the invoked method, its local parameters, and the return address of the method. The return address denotes the execution point from which, the program execution shall continue after the invoked method returns. If there is no space for a new stack frame then, the StackOverflowError is thrown by the Java Virtual Machine (JVM).
The most common case that can possibly exhaust a Java application’s stack is recursion. In recursion, a method invokes itself during its execution. Recursion one of the most powerful general-purpose programming technique, but must be used with caution, in order for the StackOverflowError to be avoided.

- stackoverflow.com

자바 프로그램에서 함수가 실행될 때 호출 스택에는 스택 프레임이 쌓인다. 스택 프레임은 호출된 메서드의 매개 변수, 지역 변수, 수행 후 돌아가야 할 메서드의 반환 주소 정보를 가지고 있다. 새 스택 프레임을 할당할 공간이 부족하면 StackOverflowError가 발생한다.

가장 흔하게 접할 수 있는 사례로는 재귀함수가 있다. 재귀 함수가 무한정 호출하면 발생할 수 있으니 함수의 base case와 inductive step을 제대로 정의하자.