当前位置:网站首页>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
边栏推荐
- Hands on deep learning (37) -- cyclic neural network
- Service developers publish services based on EDAs
- leetcode1-3
- 【Day1】 deep-learning-basics
- Hands on deep learning (39) -- gating cycle unit Gru
- Realsense d435 d435i d415 depth camera obtains RGB map, left and right infrared camera map, depth map and IMU data under ROS
- uniapp 小于1000 按原数字显示 超过1000 数字换算成10w+ 1.3k+ 显示
- Basic principle of servlet and application of common API methods
- Native div has editing ability
- Latex insert picture, insert formula
猜你喜欢
对于程序员来说,伤害力度最大的话。。。
C language pointer classic interview question - the first bullet
Realsense of d435i, d435, d415, t265_ Matching and installation of viewer environment
C language pointer interview question - the second bullet
leetcode842. Split the array into Fibonacci sequences
Rhcsa - day 13
uniapp 处理过去时间对比现在时间的时间差 如刚刚、几分钟前,几小时前,几个月前
Vs201 solution to failure to open source file HPP (or link library file)
Rhcsa12
Normal vector point cloud rotation
随机推荐
Does any teacher know how to inherit richsourcefunction custom reading Mysql to do increment?
2021-08-10 character pointer
MPLS: multi protocol label switching
Talk about scalability
什么是 DevSecOps?2022 年的定义、流程、框架和最佳实践
Vanishing numbers
Machine learning -- neural network (IV): BP neural network
The time difference between the past time and the present time of uniapp processing, such as just, a few minutes ago, a few hours ago, a few months ago
Network disk installation
Three schemes of ZK double machine room
Rhcsa operation
AUTOSAR从入门到精通100讲(106)-域控制器中的SOA
Hands on deep learning (III) -- Torch Operation (sorting out documents in detail)
7-17 crawling worms (15 points)
Button wizard business running learning - commodity quantity, price reminder, judgment Backpack
[200 opencv routines] 218 Multi line italic text watermark
AUTOSAR from getting started to mastering 100 lectures (106) - SOA in domain controllers
Reprint: summation formula of proportional series and its derivation process
【Day2】 convolutional-neural-networks
Two way process republication + routing policy