stack 과 heap의 경계?

ring9714의 이미지

stack 은 보통 아래로쌓이고 heap은 위로쌓이잖아요?
근데 심심해서 코드를 작성해서 둘이 만나게하려했는데 실제로 만나진 않네요?
힙과 스택사이에도 공간이 있나요?

코드는

#include
#include
void rec(int depth)
{
int stack[1000];

printf(depth : %d\n", depth);
printf("stack : %p ", stack); //스택 할당주소

int*ptr = (int*)malloc(sizeof(int)*1000);

printf("heap : %p\n, ptr); //힙 할당주소
rec(++depth);
}

int main()
{
int depth = 0;
rec(depth);
}

찾아보니 스택에 제한이 있다고해서 제한을 풀어줬는데도 튕길때 마지막 값이 같진 않네요

Hyun의 이미지

#include <stdio.h>
#include <stdlib.h>
 
void rec(int depth)
{
	int stack[1000];
 
	printf("depth : %d\n", depth);
	printf("stack : %p ", stack); //스택 할당주소
 
	int*ptr = (int*)malloc(sizeof(int)*1000);
 
	printf("heap : %p\n", ptr); //힙 할당주소
	if (depth < 5)
		rec(++depth);
}
 
int main()
{
	int depth = 0;
	rec(depth);
}


[hyun@its-free tmp]$ gcc test.c
[hyun@its-free tmp]$ ./a.out
depth : 0
stack : 0x7fff146b4470 heap : 0xa986b0
depth : 1
stack : 0x7fff146b34a0 heap : 0xa99660
depth : 2
stack : 0x7fff146b24d0 heap : 0xa9a610
depth : 3
stack : 0x7fff146b1500 heap : 0xa9b5c0
depth : 4
stack : 0x7fff146b0530 heap : 0xa9c570
depth : 5
stack : 0x7fff146af560 heap : 0xa9d520
[hyun@its-free tmp]$

PC 의 경우 heap 과 stack 이 너무 많이 떨어져 있네요...
실제, embedded 인 경우 stack 과 heap 이 만나기도 합니다...
ring9714의 이미지

ㅎㅎ

Stephen Kyoungwon Kim@Google의 이미지

자잘한 디테일은 제외하더라도 스택은 위에서 아래로 자라고 힙은 아래에서 위로 자라니까요. amd64에서는, 행여 둘이 붙어 있다 해도, 각각의 시작 주소 차이는 근사적으로 스택 사이즈 + 힙 사이즈만큼 나게 되죠.

Stephen Kyoungwon Kim@Google의 이미지

https://commons.wikimedia.org/wiki/File:Linux_Virtual_Memory_Layout_64bit.svg

64비트 amd + 리눅스에서는 붙어 있지 않네요.