当前位置:网站首页>Dynamic memory management and related topics
Dynamic memory management and related topics
2022-07-26 23:23:00 【hania_ w】
List of articles
1、 Why is there dynamic memory
Many people wonder , What is the significance of the existence of dynamic memory ? He made us more flexible in opening up space .
The way we have mastered to open up memory space is to open up on the stack , You can't change the size at will
int a = 20;// Open up four bytes in the stack space
char arr[10] = {
0};// Open up on the stack space 10 Bytes of contiguous space
But related to dynamic memory malloc calloc realloc Functions are opened in the heap , The memory space they open up is not fixed , It can be expanded or reduced .
2、 Introduction to dynamic memory related functions
1、mallo Function introduction

malloc The return value is a pointer to this space , The parameter is the memory space we need to open byte size .
//1、 If the development is successful , Then return a pointer to open a good space .
//2、 If the development fails , Returns a NULL The pointer , therefore malloc The return value of must be checked .
//3、 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 .
//4、 If parameters size by 0,malloc The standard is undefined , Depends on the compiler
in addition ,C Language provides a function free, It is specially used for dynamic memory release and recovery 
free The parameter of is a pointer to the space we need to free
Be careful : The space we release must be dynamically developed
malloc free Functions related to dynamic memory are contained in header files <stdlib.h> Medium 
2、calloc Function introduction

calloc The function of the function is to open up num Size is size Space of elements of , And initialize each byte of the space to 0.
int* p = (int*)calloc(10,4)
// This code means to open up 10 individual The size is 4 Bytes of space ,
// So a total of 40 The size of space in bytes
// And assign the address of the opened space to p
Be careful :malloc、calloc One difference is ,calloc The opened space will be initialized to 0,malloc=calloc+memset.
Look at the code ,calloc And malloc Function comparison 

calloc: We opened up 40 Bytes of space , It is not initialized ,calloc The function initializes to 0, This is a malloc Functions that are not available
malloc: Similarly, we are not right malloc Function to initialize , But what he printed out was 10 The same random number
3、realloc Function introduction
1、realloc Functions make dynamic memory management more flexible .
2、 Sometimes we find that the application space is too small in the past , Sometimes we think the application space is too large , That's for reasonable time memory , We will make flexible adjustments to the size of memory . that realloc Function can be used to adjust the dynamic memory size .
realloc The return value of the function points to the address of our newly opened space , Function has two arguments , The first parameter is our original spatial address , The second is the size of the space we need to open up . The unit is byte
//1、ptr Is the memory address to be adjusted
//2、size New size after adjustment
//3、 The return value is the starting memory position after adjustment .
//4、 This function adjusts the size of the original memory space ,
// The original data in memory will also be moved to new Space
//realloc(NULL,40) And malloc(40) It is equivalent.
in fact realloc There are also two cases of opening up space
Look at the picture.
Situation 1 :
Situation two :

3、 Common dynamic memory errors
1、 Yes NULL Dereference operation of pointer
// Error model
void test()
{
int *p = (int *)malloc(4);
*p = 20;// If p The value of is NULL, There will be problems
free(p);
}
In the code above , If malloc Failed to open up space , that p Is a null pointer , Dereference of null pointer is illegal
// Correct demonstration
void test()
{
int *p = (int *)malloc(4);
if(p==NULL)
{
printf("%s\n",strerror(errno));
// Print out the reason why the development failed
}
*p = 20;// If p The value of is NULL, There will be problems
free(p);
p=NULL;
}
2、 Cross border access to dynamic open space
int i = 0;
int* p = (int*)malloc(40);
if (NULL == p)
{
printf("%s\n", strerror(errno));
}
for (i = 0; i <= 10; i++)
{
*(p + i) = i;// When i yes 10 Cross border visits when
}
free(p);
p = NULL;
If you forcibly run the above code of cross-border access, the following error will appear 
3、 Use of non dynamic memory free Release
int a = 10;
int *p = &a;
free(p);
p=NULL;
If we forcibly release the non dynamic space , The program will still crash 
4、 Use free Release a piece of dynamic memory

here , Our program still crashes 
free The released space must be the first address of the space we open
5、 Multiple releases of the same dynamic memory
int *p = (int *)malloc(100);
free(p);
free(p);// Repeat release
The program still crashes 
6、 Dynamic memory forget to release ( Memory leak )
void test()
{
int* p = (int*)malloc(100);
if (NULL != p)
{
*p = 20;
}
int i = 0;
scanf("%d", &i);
if (i == 5)
{
// If someone really enters directly for the first time 5; So let's go straight back to , There is no chance to free up space
return;
}
free(p);
p = NULL;
}
int main()
{
test();
return 0;
}
4、 Flexible array
1、 A brief introduction to flexible arrays
typedef struct type
{
int i;
int a[];// Flexible array members
}type_a;
//1、 A flexible array member in a structure must be preceded by at least one other member .
//2、sizeof The size of the structure returned does not include the memory of the flexible array .
//3、 Structures that contain flexible array members use malloc () Function
// Dynamic allocation of memory , And the allocated memory should be larger than the size of the structure
// Small , To fit the expected size of the flexible array .

The structure size does not include the flexible array
2、 The use of flexible arrays

So flexible array members a, It's equivalent to getting 100 A continuous space of integer elements
3、 The advantages of flexible arrays
The first advantage is : Convenient memory release
If our code is in a function for others , You do a secondary memory allocation in it , And return the whole structure to
user . The user calls free You can release the structure , But the user doesn't know that the members in the structure also need free, So you
You can't expect users to find out . therefore , If we allocate the memory of the structure and the memory of its members at one time
了 , And return a structure pointer to the user , The user does it once free You can also free up all the memory .
The second advantage is : This is good for access speed
Continuous memory is good for improving access speed , It also helps reduce memory fragmentation
5、 Explanation of classic written examination questions
1、
void GetMemory(char* p)
{
p = (char*)malloc(100);
}
void Test(void)
{
char* str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
int main()
{
test();
return 0;
}
Look at the code above , What happens when it runs ?
The code cannot be executed at all , Why is that ?
The correct distribution should be as follows
void GetMemory(char** p)
{
*p = (char*)malloc(100);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str);// take str Send in your address
//str This point is *p Open up space
strcpy(str, "hello world\n");
printf(str);
// Release when using up
free(str);
str=NULL;
}
int main()
{
Test();
return 0;
}
2、
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
The above code runs out of chaos 
Why is that ?
3、

The code above has only one problem , There is no free space
Write it correctly
void GetMemory(char** p, int num)
{
*p = (char*)malloc(num);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
free(str);
str=NULL;
}
int main()
{
Test();
return 0;
}

边栏推荐
- 提前批到底影不影响正式批?
- Why did kylin 990 series fail to meet cortex-a77 and Mali G77?
- Signal debugging document developed by car
- 菜鸟网络面试【杭州多测师】【杭州多测师_王sir】
- [postgresql]postgresqlg use generate_ Series() function completes statistics
- 云原生微服务第一章之服务器环境说明
- Xinding acquires Ziguang holdings! Wanye enterprise: comprehensive transformation of integrated circuits!
- 实战项目:Boost搜索引擎
- Differences between PHP round and sprintf functions
- 2022-07-26: what is the output of the following go language code? A:5; B:hello; C: Compilation error; D: Running error. package main import ( “fmt“ )
猜你喜欢

Esmfold: a new breakthrough in protein structure prediction after alphafold2

Vector execution engine framework gluten announced the official open source and appeared at spark technology summit

Plato farm is expected to further expand its ecosystem through elephant swap

华裔科学家Ashe教授对涉嫌造假的Nature论文的正面回应

PostgreSQL 与 Navicat:数据库行业的中坚力量

Pyqt5 how to set pushbutton click event to obtain file address
电脑开机后内存占用过高(50%以上)

Regular expressions and bypass case recurrence

Kt6368a Bluetooth chip development precautions and problem collection - long term update

Apifox -- a better API testing tool than postman
随机推荐
2022-07-26: what is the output of the following go language code? A:5; B:hello; C: Compilation error; D: Running error. package main import ( “fmt“ )
杭州银行面试题【杭州多测师】【杭州多测师_王sir】
Kingbasees SQL language reference manual of Jincang database (3.1.1.3. currency type)
为什么我还在CSDN写文章?一段陪伴学习的历程。
Pyqt5 how to set pushbutton click event to obtain file address
Customer case | student education relies on observation cloud to create a new ecosystem of observable Smart Education
Public cloud security and compliance considerations
Incremental secure file system SFS based on C language design
SQL 基础知识
What if redis memory is full? This is the right way to deal with it
KT6368A蓝牙芯片开发注意事项以及问题集锦--长期更新
PostgreSQL 与 Navicat:数据库行业的中坚力量
Professor Ashe, a Chinese scientist, made a positive response to the suspected fake Nature paper
[flask advanced] analyze the thread isolation mechanism in flask in combination with the source code
Eureka基本使用
Typescript stage learning
Domestic DRAM will be mass produced by the end of the year, but the road ahead is still long!
程序员成长第二十九篇:如何激励员工?
逆袭黑马:数据库全栈工程师(DevDBOps)培训,把最好的课程送给您!
基本的SELECT语句