Dynamic memory of C++ study notes

Memory in a C++ program is divided into two parts:

  • Stack: All variables declared inside a function will occupy stack memory.
  • Heap: This is unused memory in the program, which can be used to dynamically allocate memory while the program is running.
  • Stack area: managed by the program, storing local variables, and automatically released by the program
  • Heap area: managed by ourselves, we create and release ourselves, and when the program ends, the program will take over and release the space.

Dynamic memory is obviously as literal as the allocation of memory is dynamic

To put it bluntly, the memory required by some variables cannot be determined by programming, it needs to be known at runtime

for example

int i;
cin >>i;
int *p =new int[i];
//这里*p指向的内存大小随着用户输入的数动态变化

To put it bluntly, static memory is immutable, and the memory size is determined by the compiler

Such as constants, constant variables (const), static variables, global variables

new and delete operators

The main advantage of new over the malloc() function is that new doesn't just allocate memory, it also creates objects.

int *i=NULL;
i=new int;//为变量请求内存
delete i;释放内存

Guess you like

Origin blog.csdn.net/m0_59054762/article/details/131266168