JD의 블로그

1. Stack vs Heap 본문

-프로그래밍 언어/알고리즘&자료구조

1. Stack vs Heap

GDong 2019. 9. 18. 00:58

1. About Main Memory

Memory is divided into smaller addressable units that are called as bytes. Every bytes have its own address. The entire memory is not used as a single unit, but it is divided into manageble pices, that are called as segment. 

 

 

2. How a Program use memory

Main mamory is divided into three sections : code section, Stack, and Heap.

If I have a program file on the hard disk and if i want to run this program, so the machine code of the program should be brought inside the main memory. 

So, the area that is occupied by the program, in the main memory, is called as "Code Section" that not be fixed. 

Once it is loaded, the CPU will start executing the program, and this program will utilize the remaining memory as divided into stack and heap.  

 

data in main function is called "activation record of main function", which is created into the Stack. 

Number of bytes taken by integer depends on the compiler, and the operating system, and the hardware. 

 

3. Static Allocation

How many bytes of memory is required by the function was decided at compile time. The size of the memory is a static value. So, when everything is done at compile time or before run time, it is called static. 

 

When I want to run sequence of programs, the machine code of these programs will be copied in code section.

These require variables, so the memory for variables will be allocated  in stack. Stack memory behaves llike a stck during the function call. 

 

4. Dynamic Allocation

How heap memory is utilized by a program. 

Heap means what? Piling up! If the things are kept one above another, or just randomly, we use the term Heap. 

So Heap is used in 2 cases. 

[1] If the things are properly organised like a tower-like thing

[2] if it is not organised and also it's looking like a tower, then also we call it as Heap.

 

Here , Heap is the term used for unorganized memory.

Heap memory should be treated like a resource. 

Program can't directly access heap memory. (only possible by using pointer!)

 

"new" means memory is allocated in heap.