当前位置:网站首页>Memory management A4
Memory management A4
2022-07-27 19:19:00 【Liu jingyiru】
First , Blogging should be done at one go , Don't wait twoorthree days , Solve and absorb the problems of the day . Then be patient , Learning requires patience .
For some content of this article, please refer to this link :C++ memory management ( Super long , The example is very detailed , Good typography )_caogenwangbaoqiang The blog of -CSDN Blog _c++ memory management
( One ):C++ Memory includes kernel space , Stack , Memory mapped segments , Pile up , Data segment , Code segment .
1. First of all, the memory here is a virtual mapped space . The physical memory depends on the performance of the hardware device . The program runs on the operating system , It will also be affected by memory . The size of memory is related to the system that executes the program . stay 32 Bit program , Most memory exists on the heap , Stack general several mb, So we often mention that because recursion is too deep , Stack overflow error .
2. The role of these five main areas : Kernel space ( It's about the operating system , Don't know for the time being ), Code segment : Used to put executable code and read-only constants . Here is generally the part that cannot be modified .
Stack And heap involve dynamic memory allocation . The stack grows downward , When executing a function , The memory units of local variables in the function can be created on the stack , At the end of the function, these storage units are automatically released . Stack memory allocation operations are built into the processor's instruction set , It's very efficient , But the allocated memory capacity is limited .
Pile up It grows upward . Store by new Allocated memory block , Their release is controlled by our application , There is usually only one new And a delete Corresponding . If the programmer doesn't release the program , So when the program is over , The operating system will automatically recycle .
Data segment Global and static variables are allocated to the same block of memory , In the past C In language , Global variables are divided into initialized and uninitialized , stay C++ There is no such distinction , They share the same memory area .
Some more , Memory mapped segments , This section will be used to store dynamic and static libraries .
( Two ) difference
1. Heap and stack .
void f()
{
int *p=new int[5]; // meaning : A pointer on the stack points to the memory of the heap , Will first determine the allocation in
The size of memory on the heap , Then call operate new Apply for memory on the heap
Then return to the first address on this memory
Essential difference : Because stack memory is managed by compiler , Heap memory is maintained by programmers . In contrast , The stack is more structured . Embodied in , Stack in and out , Follow the steps to press the stack and destroy the stack , Therefore, orderly mandatory allocation and release ensure that the allocation of stacks is orderly . But also static memory allocation ( compiled ) And dynamic memory allocation , Dynamic memory allocation is made by malloc Function to allocate . The allocation and release of the heap are discontinuous , There are many fragments in the heap .
2.delete and new:
( 3、 ... and )C++ The way of memory management in
Aim at C In language malloc-- and free,C++ We have perfected new// and delete.
A.new~delete And malloc~free contrast 【 The first group of experiments 】
B.new~delete And malloc~free Failed to open memory 【 The second group of experiments 】
C. location new expression

[A] From the analysis :1.new and delete The constructor and destructor are adjusted respectively . and malloc and free No, . And it has nothing to do with whether it is a built-in type .2. Speculative principle . The function of the pointer . Why should we open up and free up space by deleting and instantiating pointers ?
(1) principle : A pointer on the stack points to the memory of the heap , We will first determine the size of memory allocated on the heap , Then call operate new Apply for memory on the heap , Then return to the first address on this memory .
(2)new and delete Will call constructors and destructors
/*
operator new: The function actually passes malloc To apply for space , When malloc When the space application is successful, it will directly return ; Failed to apply for space , Try to implement space shortage countermeasures , If the countermeasures are changed, the user sets them , Then continue to apply , Otherwise, throw it out of order .
*/
void *__CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc)
{
// try to allocate size bytes
void *p;
while ((p = malloc(size)) == 0)
if (_callnewh(size) == 0)
{
// report no memory
// If the memory request fails , It's going to throw bad_alloc Types of abnormal
static const std::bad_alloc nomem;
_RAISE(nomem);
}
return (p);
}
/*
operator delete: The function is finally passed through free To free up space
*/
void operator delete(void *pUserData)
{
_CrtMemBlockHeader * pHead;
RTCCALLBACK(_RTC_Free_hook, (pUserData, 0));
if (pUserData == NULL)
return;
_mlock(_HEAP_LOCK); /* block other threads */
__TRY
/* get a pointer to memory block header */
pHead = pHdr(pUserData);
/* verify block type */
_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
_free_dbg( pUserData, pHead->nBlockUse );
__FINALLY
_munlock(_HEAP_LOCK); /* release other threads */
__END_TRY_FINALLY
return;
}
//free The implementation of the
#define free(p) _free_dbg(p, _NORMAL_BLOCK)
[B]operator new It's actually through malloc To apply for space , If malloc To apply for space Success goes directly back to , Otherwise, implement the countermeasures against insufficient space provided by the user , If the user provides this measure, continue to apply , Otherwise, it will throw the exception .operator delete And finally through free To free up space
operator new And operator delete function :new and delete It is an operator for users to apply for and release dynamic memory ,operator new and operator delete It's provided by the system Global function ,new Call... At the bottom operator new Global function to apply for space ,delete At the bottom through operator delete overall situation Function to free up space .
#include<iostream>
using namespace std;
int main()
{
try
{
char* p = new char[0x8fffffff];
//char* p = new char[08ffffffff];
printf("%p\n", p);
}
catch (const exception& e)
{
cout << " Memory request failed " << endl;
}
return 0;
}For objects that are not internal data types , Light use maloc/free Can't meet the requirements of dynamic objects . Object to be created at the same time to automatically execute the constructor , Objects are automatically destructed before they die . because malloc/free It's a library function, not an operator , Not in compiler control , The task of executing constructors and destructors cannot be imposed on malloc/free. therefore C++ Language needs an operator that can accomplish dynamic memory allocation and initialization new, And an operator to clean up and free memory delete.
class Test
{
public:
Test()
: _data(0)
{
cout<<"Test():"<<this<<endl;
}
~Test()
{
cout<<"~Test():"<<this<<endl;
}
private:
int _data;
};
void Test()
{
// pt Now it's just pointing to Test A space of the same size as an object , It's not an object yet , Because the constructor doesn't execute
That's ok
Test* pt = (Test*)malloc(sizeof(Test));
new(pt) Test; // Be careful : If Test When the constructor of a class has parameters , You need to pass reference here
}边栏推荐
猜你喜欢

Unity shows Kinect captured shots

C # interaction with MySQL database - MySQL configuration and addition, deletion, query and modification operations

Performance analysis of continuous time system (1) - performance index and first and second order analysis of control system

搭建阿里云+typora+Picgo图床错误分析

进行接口测试时,连接数据库,对数据源进行备份、还原、验证操作

SSM integration

2022 preparation for autumn recruitment 10W word interview sketch PDF version, with operating system and computer network interview questions

Mongodb learning notes (1) - install mongodb and its related configurations

IDEA成功连接Database但不显示表怎么办

2022备战秋招10W字面试小抄pdf版,附操作系统、计算机网络面试题
随机推荐
kettle入门级操作第一篇(读取excel、输出excel)
C语言打印菱形
JS common utils encapsulation
WinForm screenshot save C code
Code interview of Amazon
go-zero单体服务使用泛型简化注册Handler路由
New system installation mysql+sqlyog
Usage of ref keyword
Latex use - control the display position of tables or graphics
进行接口测试时,连接数据库,对数据源进行备份、还原、验证操作
101. (cesium chapter) cesium particle system - snow
汇编语言入门基础(1)
win10小技巧(1)——转移桌面位置
怎样产生标准分布或高斯分布的随机数
Nacos基本概念和单机部署
Micaz+tinyos learning notes (1)
"Testing novice encyclopedia" 5-minute quick start pytest automated testing framework
Unity display Kinect depth data
阿里云视频点播服务的开通和使用
微机原理学习笔记-通用整数指令及应用