当前位置:网站首页>Deep analysis - dynamic memory management
Deep analysis - dynamic memory management
2022-07-27 04:22:00 【Shilipo Xiaobai】
List of articles
Depth analysis : data
Depth analysis : recursive
Depth analysis : Structure
Depth analysis : Dynamic memory management
List of articles
Preface
The need for space , Sometimes the amount of space we need is known when the program is running , The way to open up space when compiling arrays is not enough . At this time, it is necessary to run the program , Open up memory in the heap area as required .
One 、 Example questions : The capacity of the address book
1. Address book requirements
The address book needs a way to open up corresponding space according to the amount of information stored
The way we usually use is to open up a fixed size array , This leads to poor flexibility in address book storage . If the space is too small , Can't put so much information . If you open up a lot of space , There is also a waste of space . Therefore, we need a new way to change the size of the development space according to the storage requirements .
Two 、 Dynamic memory functions
1. malloc
void *malloc (size_t size);
malloc: Functions that can be opened up dynamically for any type
This function applies to memory for a contiguous block of free space , And return the pointer to this space .
- If the development is successful , Then return a pointer to open a good space .
- If the development fails , Returns a
NULLThe pointer , therefore malloc The return value of must be checked . - The type of return value is
void*, therefore malloc Function doesn't know the type of open space , The user will decide when using it . - If parameters
sizeby 0,malloc The standard is undefined , Depends on the compiler .
2. calloc
void *calloc (size_t num, size_t size);
calloc: Functions that can be opened up dynamically for any type , And initialize each byte of the space to 0
This function applies to memory for a contiguous block of free space , And return the pointer to this space , And initialize each byte of the space to 0.
- If the development is successful , Then return a pointer to open a good space .
- If the development fails , Returns a
NULLThe pointer , therefore malloc The return value of must be checked . - The type of return value is
void*, therefore calloc Function doesn't know the type of open space , The user will decide when using it . - If parameters
sizeby 0,calloc The standard is undefined , Depends on the compiler . - The function is for
numSize issizeThe elements of open up a space , And initialize each byte of the space to 0. - And functions malloc The only difference is calloc Initializes each byte of the requested space to full before returning the address 0.
3. realloc
void *realloc (void* ptr, size_t size);
realloc: Function can adjust the size of dynamic development memory
- realloc Functions make dynamic memory management more flexible .
- Sometimes we find that the application space is too small in the past , Sometimes we think the application space is too large , In order to make rational use of memory , We often make flexible adjustments to the size of memory . that realloc Function can be used to adjust the dynamic memory size .
ptrIs the memory address to be adjusted .sizeIs the adjusted new size .- The return value is the starting memory position after adjustment .
- This function adjusts the size of the original memory space , It will also move the data in the original memory to a new space .
realloc There are two ways to adjust memory space :
There is enough space behind the original space : To expand memory, add space directly after the original memory , The original spatial data does not change .

When there is not enough space after the original space , The way to expand is : Find a suitable size of continuous space on the heap space Use . This function returns a new memory address .

4. free
void free (void* ptr);
free: Function is used to release memory opened dynamically
- If parameters
ptrThe pointed space is not opened dynamically , that free The behavior of a function is undefined . - If parameters
ptryes NULL The pointer , Then the function does nothing .
3、 ... and 、 Common dynamic memory errors
1. Yes NULL Dereference operation of pointer
void test() {
int *p = (int *)malloc(INT_MAX/4);
*p = 20; // If p The value of is NULL, There will be problems
free(p);
}
2. Cross border access to dynamic open space
void test() {
int i = 0;
int *p = (int *)malloc(10 * sizeof(int));
if(NULL == p) {
exit(EXIT_FAILURE);
}
for(i=0; i<=10; i++) {
*(p+i) = i;// When i yes 10 Cross border visits when
}
free(p);
}
3. Use of non dynamic memory free Release
void test() {
int a = 10;
int *p = &a;
free(p); // Free up non dynamic space
}
4. Use free Release a piece of dynamic memory
void test() {
int *p = (int *)malloc(100);
p++;
free(p); //p No longer points to the start of dynamic memory
}
5. Multiple releases of the same dynamic memory
void test() {
int *p = (int *)malloc(100);
free(p);
free(p);// Repeat release
}
6. Dynamic memory forget to release ( Memory leak )
void test() {
int *p = (int *)malloc(100);
if(NULL != p) {
*p = 20;
}
}
int main() {
test();
}
summary
Dynamically allocated memory consists of malloc Equal correlation function assignment , This function returns a pointer to a memory block with a specified number of bytes . This memory is free After the function is released, it can be reused ,free The function takes the address of the memory block as the parameter . Dynamic memory management makes our program more flexible , It provides more possibilities for our program .
边栏推荐
- ArrayList与LinkedList区别
- 2022 operation of simulated examination question bank and simulated examination platform for safety production management personnel of hazardous chemical production units
- 标准C语言11
- Echart柱状图中数据显示在图上方
- List Simulation Implementation
- The real digital retail should have richer connotation and significance
- Apachecon Asia preheating live broadcast incubator theme full review
- Rust:axum learning notes (1) Hello World
- 搜索旋转排序数组
- [Code] sword finger offer 04 search in two-dimensional array
猜你喜欢

人很话不多,工程师不耍嘴皮子

Subject 3: Jinan Zhangqiu line 2

list模拟实现

BSN IPFS(星际文件系统)专网简介、功能、架构及特性、接入说明

Plato Farm全新玩法,套利ePLATO稳获超高收益

Analysis of three common kinematic models of mobile chassis

F - Pre-order and In-order(Atcoder 255)

Ribbon-负载均衡原理及部分源码

js三种遍历数组的方法:map、forEach、filter

Ant JD Sina 10 architects 424 page masterpiece in-depth distributed cache from principle to practice pdf
随机推荐
二叉树的坡度
ISG指数显示,亚太区IT和商业服务市场在第二季度出现大幅下滑
Daily question 1: parity tree
F - Pre-order and In-order(Atcoder 255)
项目参数做成可配置项,@ConfigurationProperties注解的使用
List Simulation Implementation
EVT interface definition file of spicy
webpack打包vue项目添加混淆方式,解决缓存问题
JMeter download and installation
Preliminary understanding of NiO
[small sample segmentation] msanet: multi similarity and attention guidance for boosting few shot segmentation
2022 retraining question bank and answers for main principals of hazardous chemical business units
Subject 3: Jinan Zhangqiu line 3
【机器学习网络】BP神经网络与深度学习-6 深度神经网络(deep neural Networks DNN)
整理字符串
How CentOS installs mysqldump
Slope of binary tree
Subject 3: Jinan Zhangqiu line 6
influxDB 基础了解
Remember the major performance problems caused by a TCP packet loss