오늘은 뭔가 서로서로 개념들이 연관되면서 하나의 퍼즐이 마춰져간다!! 이 감을 잊어버리기전에 정리정리.
포인터.. 레퍼런스 ... 결국 컴퓨터위에서 작동하는걸 이해하기 위해서 기본기가 중요했다. 메모리 레이아웃 정리부터 형상화해서 정리하기.
여기서 말하는 memory layout 은 memory 를 사용하는 모든 장치들에 통용되는것! ex) RAM , ROM..
1. text segment: The text segment is also known as the code segment. When we compile any program, it creates an executable file like a.out, .exe, etc., that gets stored in the text or code section of the RAM memory. OKAY
2. Data section: main() 밖에 선언된 Variables들로
(A data segment is a virtual address space of a program that contains all the global and static variables which are explicitly initialized by the programmer.)
- initialized global ,local 타입과
- unintialized global, local 타입이 있다!.
#include<stdio.h>
char a; // uninitialized global variable..
char string[] = "javatpoint"; // global variable stored in initialized data segm
int main()
{
static int a; // uninitialized static variable.. 이건 main 안에 선언됬으니 stack에!
return 0;
}
여기까지가 static memory layout. 즉 컴파일링할때 이미 정해진 영역
3. stack : 요놈... 아주 중요하지 기본적으로 선언되는 모든 variable 과 function 들이 stack에 속하며 address는 메모리의 가장 큰값부터 아래로 decreasing 되며 저장된다. 여기서 point로 선언된 variable도 포함된다.
4. Heap: 다이나믹 메모리이며 메모리주소는 밑에서부터 위로 올라가며 증가된다. c에서는 malloc() 과 calloc() 'c++에서는 new' 로 선언해줄수있다.
#include<stdio.h>
int main()
{
int *ptr = (int*)malloc(sizeof(int)) ; // memory gets allocated in the heap segment.
return 0;
}
여기까지 memory layout 종류를 설명끝
자 여기서부터는 heap 과 stack이 어떻게 형상황된 메모리 레이아웃에 저장되는지 설명! 이에대해 정말 설명 잘해놓은 illnois ! https://courses.engr.illinois.edu/cs240/sp2021/notes/virtualMemory-heap-stack.html#:~:text=In%20all%20C%20and%20C%2B%2B,pointer%20to%20%E2%80%9Cheap%20memory%E2%80%9D.
정리하기보다 여기서 다시 훓어보는게 더 시각적으로 들어온다 !
그리고 이건 geeksforgeeks에서 설명한 stack 과 heap의 차이점 설명.
1.stack은 allocation과 deallocation이 알아서되서 메모리 누수가없다 반면 heap은 사용자가 일일이해줘야되서 누수가 될수있다.
2. 메모리부족현상은 stack에서 더 자주일어나고 heap에서는 파편화 문제가 있다.
3. stack은 flexible하지 못하지만 안정적이고 heap은 flexible하지만 위험하다( 코드가 뻑이날수있다.ㅠ c++ 에서는 smart pointer를 사용하면 자동으로 해제해주는 기능이 만들어졌다!)
지금까지 토픽을 정리 하자면
1. 메모리 레이아웃의 큰 틀을 정리하였고
2. heap과 stack이 variable을 어떻게 메모리에 저장하고 해제하는지 위에 블로그에서 설명한것으로 공부하였다.
3. stack vs heap을 나열해봤다.
다음으로는
pointer vs reference 를 다뤄야지.
'Language > C++' 카테고리의 다른 글
[c++] 깊은 복사(Deep copy)와 얕은 복사(shallow copy) (0) | 2022.11.23 |
---|---|
[c++][pointer vs reference 정복 2] Pass by value vs Pass by reference (0) | 2022.11.18 |
[Geeks][Reference] References in C++ (0) | 2022.11.15 |
[oop in C++] Static members (0) | 2022.10.12 |
[c++] <this> pointer 오호... (0) | 2022.10.11 |
댓글