当前位置:网站首页>Dynamic memory management
Dynamic memory management
2022-07-20 13:17:00 【*insist】
List of articles
1.1 Various variables 、 Storage location of constants
When we code, we always define it in various places Define various constants 、 Variable , So do we know where they exist ?
Take a look at this code
#include<iostream>
using std::cout;
using std::endl;
using std::exception;
// Define global variables Including global static variables
int aa;
const int ad=0;
static int bb;
int main1()
{
// Definition of various local variables
int a = 0;
const int b = 0;
static int c = 0;
char arr[] = "abd";
const char* p = "gneij";
char* p1 = (char*)malloc(sizeof(char) * 10);
// Print their address
cout << " The addresses of each variable are as follows :" << endl;
cout << "aa:" << &aa << endl;
cout << "ad:" << &ad << endl;
cout << "bb:" << &bb << endl;
cout << "c:" << &c << endl;
cout << "p:" << (void*)p << endl;
cout << endl;
cout << "a:" << &a << endl;
cout << "b:" << &b << endl;
cout << "arr:" << (void*)arr << endl;
cout << endl;
cout << "p1:" << (void*)p1<<endl;
return 0;
}
The operation results are as follows :
** It can be observed through the operation results aa bb c Your address is similar It shows that they exist in the same area **
ad p Your address is similar The instructions are placed in the same area
a b arr Their addresses are similar They also exist in the same area
p1 There is an area alone
among aa bb c in aa Global variable bb Is a global static variable c Is a local static variable Global ordinary or static variables are stored in Static zone ( Data segment )
ad Is a global constant p The printed address is actually a constant string “gneij" The address of Visible global constants and constant characters / String is stored in The constant area ( Code segment )
a b It's a local variable arr Pointer variable refers to the data of the array on the stack All exist On the stack
p1 Although it's a pointer It's pointing malloc Space created on the heap so p1 Point to space Pile it up
1.2c/c++ Distribution of memory
From the above, we know that the language memory includes The constant area Static zone The stack area Heap area etc.
2.1c++ Dynamic memory management
2.1.1c++ of use new and delete Operator for dynamic memory management
c++ Class... Is introduced Classes can contain various types Including built-in types and custom types It's still used at this time c Dynamic memory management is very inconvenient to manage For example, a class has multiple pointer variables pointing to multiple spaces stay c You have to use them one by one free Release however c++ There are destructors It can all be directly in the destructor free Each space Then call the destructor .
- therefore c++ Has its own dynamic memory management Namely new and delete The operator
new Used to create objects ( Including opening up space ) delete Used to clean up object resources and free up space
among new A single space is direct type p=new type( Initialize parameters )*
If it is new A continuous space is type p=new type[n];*
class Stack
{
public:
Stack(int size = 4)
{
cout << "Stack(int size=4)" << endl;
_top = 0;
_capacity = size;
_a = new int[size];
}
~Stack()
{
cout << "~Stack()" << endl;
delete[] _a;
_top = _capacity = 0;
}
void print()
{
cout << "void print()" << endl;
}
private:
int* _a;
int _top;
int _capacity;
};
int main()
{
Stack* st=new Stack(10);
Stack* p=new Stack[10];
delete st;
delste[] p;
return 0;
}
The above code is executed as follows :
Be careful : In the above code Stack Class constructors and destructors have output flags The delegate is called
We new One Stack When the object It will output Stack The flag that the constructor of is called
delete When an object It will output Stack The flag that the destructor of is called
We can draw Conclusion :new Creating objects is not just about opening up space The constructor of the class will also be called to initialize the object delete The destructor of the class will be called to clean up resources Release space after
In depth analysis of :
Actually new It's a function operator new Functions and location new Combined
among operator new It's encapsulation again malloc Got It includes more than malloc The function of opening up space It will also throw exceptions after the failure of opening up space Not with malloc Returns a null pointer
location new Is responsible for explicitly calling the constructor Initialize the created object
Be careful :operator new () It's a function Not an operator overload !!
delete At the bottom through operator delete overall situation
Function to free up space But the call operator delete The destructor will be called to clean up resources before
- And operator new() Corresponding also operator delete() It's just a function It's not overloading !
location new The format of
// location new The format of
//new( The address of the space )type( Parameter initialization )
// for example :
Stack* st= operator new(sizeof(Stack));// adopt operator new Function opens up space
new(st1)Stack(4);// location new Initialize object 4 Is the parameter of the constructor
location new Usage scenarios of
location new In practice, expressions are generally used with memory pools . Because the memory allocated by the memory pool is not initialized , So if it's custom
Object of type , Need to use new The definition expression is displayed and the constructor is initialized
- Extension : Successive new delete The efficiency is not high because you have to apply to the operating system Pooling technology can be used to solve this problem Is to use memory pool technology Make every time not to ask for space from the operating system Instead, open up space in your own pool This will greatly improve efficiency It's like using your own things is very convenient It's not very convenient to borrow other people's things operator new and operator delete Can overload Then you can write one by yourself Use memory pool to realize !!!!
2.1.2c of use malloc、calloc、realloc、free Realize the management of dynamic memory
void* malloc (size_t size);
void* calloc (size_t num, size_t size);
void* realloc (void* ptr, size_t size);
malloc It is to apply to the operating system to open up a given space in bytes on the heap If the application is successful, the address pointing to the space will be returned Otherwise return null pointer
calloc Also open up space Their ratio malloc One more parameter num Is the number of types of development size Is the size of the type If open 10 individual int The space of type is
int* p=(int*)calloc(10,sizeof(int));
It is worth noting that calloc comparison malloc It's not just more than one parameter and calloc It will also initialize the opened space as 0 This is a malloc What you don't have !
realloc Is to continue to open up space behind a given space The first parameter is the address of the opened space The second parameter is the amount of space to be opened up
free: When we no longer use the open space, we can use free( Space address ) Of Way to free up space , It is safer to set the pointer to null
2.1.3 The difference between dynamic memory management and dynamic memory management
new delete and malloc free The difference between :
1.new and delete It's the operator malloc and free Is the function
2.new Will initialize the opened space however malloc Can't
3.malloc When opening up space, you need to use sizeof The size of the type trouble new There is no need to Just follow the type directly If there are multiple objects, add one [] that will do
4.malloc The return type of is void After opening up, you need to force type conversion however new Unwanted
5.malloc If you fail to open a space, the null pointer is returned. You need to manually judge whether it is a null pointer and then know whether the space is successfully opened and new You don't have to If new Open up space
Failure will throw exceptions We just need to catch exceptions
6.new It will automatically call the constructor of the development object for initialization delete The destructor of the object will be called to clean up resources before space is released Free up space malloc free Will not be
3.1 What is memory leak
Memory leak is memory lost or pointer lost ?
You should know this question The memory leak is the loss of the pointer Instead of losing memory Memory is not lost
If we don't release after opening up space Make the address of this block space lost You cannot free space through this address This space will be occupied all the time without returning it to the operating system The memory of the operating system is getting smaller and smaller Long running programs process If there is a memory leak problem As time goes by Memory will be less and less Finally, the operating system may crash !!!
边栏推荐
- Paper reading: linknet: expanding encoder representations foreefficient semantic segmentation
- C leetcode notes 5-dynamic sum of one-dimensional array
- PHP实现执行定时任务的几种思路详解
- Stm32+bh1750 photosensitive sensor obtains light intensity
- dotnet 读 WPF 源代码笔记 渲染收集是如何触发
- Feign入门之快速实战
- Druid configuration and monitoring
- Nacos配置管理——统一配置管理
- 牛津大学:许多常见失眠药物缺乏长期安全数据
- c# LeetCode刷题笔记5- 一维数组的动态和
猜你喜欢
早期肺结核检测
Paper reading: linknet: expanding encoder representations foreefficient semantic segmentation
从工程师到技术leader思维升级
STM32+BH1750光敏传感器获取光照强度
OpenHarmony littlefs文件系统存储结构与IO性能优化分析
Hackers crack gambling website vulnerabilities and "collect wool" 100000 per month
Qt | 通过创建一个简单项目了解Qt Creator
Notepad++ software installation tutorial
Feign入门之快速实战
RK3399平台开发系列讲解(进程间通信)14.10、如何查看进程调度的信息
随机推荐
The SQL seen here will be truncated. Is there any way to see the complete SQL?
手写一个js工具库并且发布到npm上,并且添加eslint和jest单元测试详细教程和解决方案
在 IDEA 里下个五子棋不过分吧?
日期类的简易实现
Live short video source code - the development sequence of live short video source code is five steps
Reading the paper: retreating atmosphere revolution for semantic image segmentation
Panda3D 获取鼠标位置、Panda3D任务管理器
How to deal with repeated consumption of MySQL data read by Flink
dotnet 读 WPF 源代码笔记 渲染收集是如何触发
Nacos集群搭建(转载)
Scratch judge leap year electronic society graphical programming scratch grade examination level 4 true question and answer analysis June 2022
十年架构五年生活-02第一份工作
Several small open source projects of mine over the years
c# LeetCode刷题笔记4-拿硬币
How to carry out "small step reconstruction"?
Feign的自动装配以及熔断降级
shell中的特殊符号
postgresql 两个月份,如何计算一共有几个月?
Shopify卖家:分享做社交媒体营销的几个技巧!
牛津大学:许多常见失眠药物缺乏长期安全数据