The foundation is the top priority ~ the heap and stack in memory

Memory is divided into 5 areas, they are heap, stack, free storage area, global/static storage area and constant storage area .

Stack first-in-last-out (FILO—First-In/Last-Out)

It is the memory area for variables that are allocated by the compiler when needed and automatically cleared when not needed. The variables inside are usually local variables, function parameters, etc. (In C#, value types are stored on the stack)

Heap first in first out (FIFO—first in first out)

It is those memory blocks allocated by new, and their release is ignored by the compiler and controlled by our application. Generally, a new corresponds to a delete. If the programmer does not release it, the operating system will automatically recycle it after the program ends. (In C#, reference types are stored on the heap)

free storage area

It is the memory block allocated by malloc, etc., which is very similar to the heap, but it uses free to end its life.

global/static storage

Global variables and static variables are allocated to the same memory. In the previous C language, global variables were divided into initialized and uninitialized. In C++, there is no such distinction. They occupy the same memory area.

constant memory

This is a relatively special storage area. They store constants and are not allowed to be modified (of course, you can also modify them through illegal means, and there are many ways)

Example - Stack

int a=3;
int b=3;

The compiler first processes int a = 3; first, it will create a memory space with a variable a in the stack, and then look for an address with a literal value of 3. If not found, it will open an address to store the literal value of 3, and then Point a to the address of 3. Then process int b= 3; after creating the reference variable of b, since there is already a literal value of 3 in the stack, it will point b directly to the address of 3. In this way, a and b both point to 3 at the same time.

Example - Heap

public class MyInt
{ publicint MyValue; }
public MyInt AddFive(int pValue) { MyInt result = new MyInt(); result.MyValue = pValue + 5; return result; }

The method and its parameters are placed on the stack, and then control is passed to the AddFive() instruction on the stack.

Thanks for reading!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324861615&siteId=291194637