C#

C# - stack 주소와 heap 주소 찾기

kark 2024. 7. 25. 18:26
728x90

Stack 메모리 주소 확인하는 방법

string a = "안녕하세요";
string b = a;

 

a 와 b 는 스택영역에서 각자의 주소를 갖고 하나의 heap 메모리를 참조하고 있는 상황이다.

 

&변수명 으로 조사식을 확인해보면

 

해당 문자열 참조변수의 크기는 8byte로 해당 주소는 스택영역의 주소임을 알 수 있다.

 

Heap 메모리 주소 확인하는 방법

 

string a = "안녕하세요";
string b = a;
a = "안녕하세요2";
string c = "안녕하세요";

GCHandle handle = GCHandle.Alloc(a, GCHandleType.Pinned);
GCHandle handle2 = GCHandle.Alloc(b, GCHandleType.Pinned);
GCHandle handle3 = GCHandle.Alloc(c, GCHandleType.Pinned);

IntPtr address = handle.AddrOfPinnedObject();
IntPtr address2 = handle2.AddrOfPinnedObject();
IntPtr address3 = handle2.AddrOfPinnedObject();

Console.WriteLine($" a 주소 : {address}");
Console.WriteLine($" b 주소 : {address2}");
Console.WriteLine($" c 주소 : {address3}");

 

b 와 c 의 heap 주소는 하나로 같아야하며 a 는 별도의 heap 메모리공간을 참조해야한다.

c = a 로 할당하지 않고, b 의 값처럼 "안녕하세요" 데이터는 리터럴로 인해 같은 heap 주소가 같아야함