2005년 5월 25일 수요일

C++의 메모리 공간(heap, stack)에 따른 주소

$ uname -a
Linux ob.ds.neowiz.com 2.4.20-8smp #1 SMP Thu Mar 13 17:45:54 EST 2003 i686 i686 i386 GNU/Linux

$ cat /etc/redhat-release
Red Hat Linux release 9 (Shrike)

$ cat /proc/cpuinfo
Intel(R) Xeon(TM) CPU 2.40GHz x 2

$ cat ./addr.cpp
#include <iostream>

using namespace std;

int main()
{
    int a = 10;
    int *b = new int();
    *b = 20;

    cout << "a : " << a << endl;
    cout << "&a : " << &a << endl;
    cout << "b : " << b << endl;
    cout << "&b : " << &b << endl;
    cout << "*b : " << *b << endl;

    delete b;

    return 0;
}
[ilashman@ob cpp_test]$ ./addr
a : 10
&a : 0xbfffdac4
b : 0x8049ce0
&b : 0xbfffdac0
*b : 20

-------------------------
IA32, linux의 경우는 stack일 때 0xbf로 시작하고 heap일때 0x80 부터 allocation을 시작하는 것 같다.
각 환경의 특성을 알아두면 메모리 관련 문제에서 디버깅할 때 변수의 주소를 찍어봐서 디버깅 할 수 있다.
예를 들어 new로 할당해서 heap에 들어가 있을 것으로 가정했는 데,
주소가 stack이라면 중간에 임시 객체가 생겨서 casting, copy constructor, assign 등이 일어났음을
암시할 수 있다.
혹은 share하는 변수(or static 변수)가 정말로 같은 곳을 가리키고 값이나 lock을 공유하는 지 알 수 있다.

댓글 없음:

댓글 쓰기