Rylah's Study & Daily Life

Modern C++ : 01. Memory Structure - Variables Types2 (변수 타입 in Memory) 본문

Study/C++

Modern C++ : 01. Memory Structure - Variables Types2 (변수 타입 in Memory)

Rylah 2022. 2. 3. 05:23

 

#include <iostream>
struct ST
{
	int a; // 4 bytes
	int b; // 4 bytes
};
struct ST2
{
	long a; // 8 bytes
	int b; // 4 bytes
	short c; // 2 bytes
};

class Cat
{
public:
	void printCat(); // ?
private:
	int age;	  // 4 bytes
	float weight; // 4 bytes
};

int main()
{
	std::cout << "Size of Struct : " << sizeof(ST) << std::endl;
	std::cout << "Size of Struct : " << sizeof(ST2) << std::endl; // 컴파일러에 따라서 16이 나올 수 있음
	std::cout << std::endl;

	std::cout << "Size of Class      : " << sizeof(Cat) << std::endl; // 8? or ?
	Cat cat1;
	Cat cat2; 
	std::cout << "Size of Object     : " << sizeof(cat1) << std::endl; // Member Area
	Cat* catPtr = &cat1;
	std::cout << "Size of Object ptr : " << sizeof(catPtr) << std::endl; // 8
	return 0;
}

MSVC 컴파일러는 long이 4bytes이며 4 + 4 + 2는 10bytes가 나와야하지만 padding이 들어가면서 12bytes로 추정된다.

 

#include <iostream>
int foo(int arg) 
{
	int a = 0;
	int b = 1;
	int d = arg + a + b;
	return d;
}

int main()
{
	int a;
	double b;
	bool c;
	int d = foo(1);
	return 0;
}

 

사실 이렇게 쌓이는 것은 거짓말이다.

 

이해를 돕기 위해서 조금 자세히 쓴 것이지 실질적으로 미리 이렇게 할당된 것을 탐색하는 것은 아니다.

d
c
b
a

이 구성은 이미 정해져있고 Function Call이 되는 순간 한번에 Allocation이 되고 해제가 되고 한다. 

Stack Frame 이야기는 다음으로 넘긴다.

 

출처 : https://youtu.be/qj8U_-3HhcA