Language/C
[따배씨] 9.6 재귀 호출 ~ 9.7 재귀호출과 스택
migrationArc
2021. 5. 30. 16:09
따배씨 - 따라하며 배우는 C언어
9강 함수
9.6 재귀 호출 Recursion
- 재귀 함수 : 함수가 자기 자신을 호출하는 함수
#include <stdio.h>
void my_func(int);
int main(){
my_func(1);
return 0;
}
void my_func(int n){
printf("Level %d, address of variable n = %p\n", n, &n);
my_func(n + 1);
}
// Level 1, address of variable n = 0x7ffeefbff46c
// Level 2, address of variable n = 0x7ffeefbff44c
// Level 3, address of variable n = 0x7ffeefbff42c
// Level 4, address of variable n = 0x7ffeefbff40c
// Level 5, address of variable n = 0x7ffeefbff3ec
// .....
// 무한 호출
- 메모리 주소의 차이가 크게 남
- 프로그램이 호출 될 때 마다, stack 메모리에 변수 뿐만 아니라 프로그램도 쌓이게 됨
- 재귀호출로 stack 에 큰 부담이 갈 수 있음
- stack 메모리가 가득 차면, stack overflow error 발생
- 재귀호출은 무한루프 구현을 위해 사용하지 않음
- 재귀 호출의 조건을 걸어주어서 구현해야함
#include <stdio.h>
void my_func(int);
int main(){
my_func(1);
return 0;
}
void my_func(int n){
printf("Level %d, address of variable n = %p\n", n, &n);
if (n < 4)
my_func(n + 1);
}
- 4번 호출되고 종료
9.7 재귀호출 Recursion 과 스택 Stack
#include <stdio.h>
void my_func(int);
int main(){
my_func(1);
return 0;
}
void my_func(int n){
printf("Level %d, address of variable n = %p\n", n, &n);
if (n < 4)
my_func(n + 1);
printf("Level %d, address of variable n = %p\n", n, &n);
}
// Level 1, address of variable n = 0x7ffeefbff46c
// Level 2, address of variable n = 0x7ffeefbff44c
// Level 3, address of variable n = 0x7ffeefbff42c
// Level 4, address of variable n = 0x7ffeefbff40c
// Level 4, address of variable n = 0x7ffeefbff40c
// Level 3, address of variable n = 0x7ffeefbff42c
// Level 2, address of variable n = 0x7ffeefbff44c
// Level 1, address of variable n = 0x7ffeefbff46c
- level 이 같을 때, n 의 주소값은 같음
- 재귀함수의 호출에서의 stack
- 재귀함수의 호출 시 변수 메모리 공간 뿐만 아니라, 함수가 동작하기 위한 공간도 같이 stack 에 쌓임
- stack frame
이 글의 모든 사진과 내용의 출처는 홍정모 교수님께 있음을 알려드립니다.
http://blog.naver.com/atelierjpro
실리콘 밸리의 프로그래머 : 네이버 블로그
안녕하세요! 홍정모 블로그에 오신 것을 환영합니다. 주로 프로그래밍 관련 메모 용도로 사용합니다. 강의 수강하시는 분들은 홍정모 연구소 카페로 오세요.
blog.naver.com
http://www.inflearn.com/course/following-c
홍정모의 따라하며 배우는 C언어 - 인프런 | 강의
'따배씨++'의 성원에 힘입어 새롭게 개발된 C 언어로 시작하는 프로그래밍 입문 강의입니다. '따배씨'와 함께 프로그래밍 인생을 업그레이드 해보세요., 따라하며 배우는 C언어 '따배씨++'의 성원
www.inflearn.com