当前位置:网站首页>Dynamic memory management
Dynamic memory management
2022-07-04 10:24:00 【sqjddb】
One : Why dynamic memory allocation
int a=0; // Open up four bytes in the stack area
char ch[20]; // Open up... In the stack area 20 byte
The space size of the above memory development is fixed , But the need for space , It's not just that .
Sometimes the amount of space we need is known when the program is running , At this time, you can only try dynamic memory development .
The stack area :
Ordinary local variables allocate space in the stack , The variables created above are destroyed when they are out of scope .
Heap area :
Release is usually assigned by the programmer , If programmers don't release , It may be recycled by the operating system at the end of the program , The above figure shows some dynamic memory functions .
Static zone :
By static The modified variables are stored in the data section ( Static zone ), Variables created above , Not until the end of the program
Two : Dynamic memory functions
1.malloc
This function applies to memory for a contiguous block of free space , And return the pointer to this space .
Examples of successful space development :
int*p = (int*)malloc(40);
If the development is successful , Then return a pointer to open a good space .
malloc The type of return value is void* , therefore malloc Function doesn't know the type of open space , Here, the returned pointer is cast to an integer pointer , The specific type of pointer to be converted is determined according to the requirements when using .
Examples of failed space opening :
int* p = (int*)malloc(1000000000*sizeof(int)); // The given parameter is too large
If the development fails , Returns a NULL The pointer , therefore malloc The return value of must be checked .
Last note , If parameters size by 0,malloc The standard is undefined , Depends on the compiler .
2.free
It is specially used for dynamic memory release and recovery 
void free (void* ptr);
If parameters ptr The pointed space is not opened dynamically , that free The behavior of a function is undefined .
If parameters ptr yes NULL The pointer , Then the function does nothing .
3.calloc
calloc Function is also used for dynamic memory allocation 
The function is for num Size is size The elements of open up a space , And put the space Each byte is initialized to 0.
And functions malloc The only difference is calloc Initializes each byte of the requested space to full before returning the address 0.
Open up and release examples :
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p = (int*)calloc(10, sizeof(int));
if(NULL != p)
{
// Use space
}
free(p);
p = NULL;
return 0;
}
4.realloc
Sometimes we find that the space applied for in the past is too small or too large , In order to make rational use of memory , The size of memory should be flexibly adjusted . realloc Function can be used to adjust the dynamic memory size .
void* realloc (void* ptr, size_t size);
ptr Is the memory address to be adjusted
size It's a new size after adjustment
The return value is the starting memory position after adjustment
Use realloc There are two situations 
situation 1— Add space directly after the original memory , The original spatial data does not change .
situation 2 — When there is not enough space after the original memory space , Find another continuous space of appropriate size on the heap to use , The size of this continuous space is size, The original space is released , Move data to new space , Function returns the address of the new space .
realloc You may not find a suitable space , Return at this time NULL
3、 ... and : Common dynamic memory usage errors
1 Yes NULL Dereference operation of pointer
int *p = (int *)malloc(INT_MAX/4);// The given parameter is too large, and the development fails to return NULL
*p = 20;// Yes NULL Quoting
2 Cross border access to dynamic open space
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
int a = 10;
int *p = &a;
free(p);
4 Use free Release a piece of dynamic memory
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
int *p = (int *)malloc(100);
free(p);
free(p);// Repeat release
6 Dynamic memory forget to release
Memory leak : Means in the program The heap memory that has been dynamically allocated is not released or cannot be released by the program for some reason , Cause the waste of system memory , Causes the procedure to run the speed to slow down even the system crashes and so on the serious consequence .
Classic problem of dynamic memory usage errors :
subject 1
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
①Test Function call GetMemory Use value passing ,p It's just str A temporary copy of ,str The value of is not modified , Still NULL, At this time to use strcpy And print , There will be no content displayed .
②GetMemory When the function returns , Temporary variable p The destruction , There is no pointer to the dynamically opened space , There was no release , Memory leak .
The correct way to write it is as follows
char* GetMemory(char* p)
{
p = (char*)malloc(100);
return p;
}
void Test(void)
{
char* str = NULL;
str = GetMemory(str);
strcpy(str, "hello world");
printf(str);
free(str);
str = NULL;
}
You can also change the value transfer to reference
void GetMemory(char** p)
{
*p = (char*)malloc(100);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str);
strcpy(str, "hello world");
printf(str);
free(str);
str = NULL;
}
subject 2
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
GetMemory The stack space occupied by local variables is calling GetMemory After being released , It doesn't make sense to return the address of a local variable , It is illegal to access memory through the address of the returned local variable .
Example :
subject 3
void GetMemory(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
There is no space for dynamic development , The correct ones are as follows
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
free(str);
str=NULL;
subject 4
void Test(void)
{
char *str = (char *) malloc(100);
strcpy(str, "hello");
free(str);
if(str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
Use free after ,str Not set as NULL,str Not null pointer , It is illegal to use it to access memory , Remember to use free After the empty
边栏推荐
- Architecture introduction
- Hands on deep learning (37) -- cyclic neural network
- Kotlin set operation summary
- 7-17 crawling worms (15 points)
- Baidu R & D suffered Waterloo on three sides: I was stunned by the interviewer's set of combination punches on the spot
- [200 opencv routines] 218 Multi line italic text watermark
- leetcode1229. Schedule the meeting
- Development guidance document of CMDB
- 六月份阶段性大总结之Doris/Clickhouse/Hudi一网打尽
- El Table Radio select and hide the select all box
猜你喜欢

Qtreeview+ custom model implementation example
Si vous ne connaissez pas ces quatre modes de mise en cache, vous osez dire que vous connaissez la mise en cache?

今日睡眠质量记录78分

Devop basic command

Static comprehensive experiment ---hcip1

Basic principle of servlet and application of common API methods

RHCE - day one

Hands on deep learning (III) -- Torch Operation (sorting out documents in detail)

Pcl:: fromrosmsg alarm failed to find match for field 'intensity'

Use the data to tell you where is the most difficult province for the college entrance examination!
随机推荐
Rhcsa - day 13
有老师知道 继承RichSourceFunction自定义读mysql怎么做增量吗?
Devop basic command
Delayed message center design
Work order management system OTRs
Development guidance document of CMDB
【Day1】 deep-learning-basics
Dynamic address book
RHCE - day one
PHP code audit 3 - system reload vulnerability
Does any teacher know how to inherit richsourcefunction custom reading Mysql to do increment?
Two way process republication + routing policy
Introduction to extensible system architecture
Rhcsa day 10 operation
If the uniapp is less than 1000, it will be displayed according to the original number. If the number exceeds 1000, it will be converted into 10w+ 1.3k+ display
A little feeling
Latex arranges single column table pictures in double column format articles
Some summaries of the third anniversary of joining Ping An in China
2020-03-28
Hands on deep learning (41) -- Deep recurrent neural network (deep RNN)