当前位置:网站首页>[C language] dynamic memory management
[C language] dynamic memory management
2022-07-28 06:46:00 【HandsomeDog_ L】
Catalog
1. Why is there dynamic memory allocation
2. Dynamic memory allocation function
3. Classical written examination questions
5. Examples of common dynamic memory errors
2. Cross boundary access to the space opened up by dynamic memory
4. Release the same space multiple times
1. Why is there dynamic memory allocation
The stack area :
The size of the space is fixed , Array length must be specified when declaring an array , Compile time allocation exists within the required ·
Sometimes , The memory space we need is not known until the program is running , Therefore, dynamic memory development is needed .
2. Dynamic memory allocation function
Because these functions are C Library functions provide , So the header files are <stdlib.h>
a.malloc
void* malloc (size_t size);
The functionality :
- Apply for a piece of memory Continuously available Space , And return the pointer to this space .
It's a success , Returns a pointer to the opened space .
Failed to open up , Return to one NULL The pointer , therefore malloc The return value of must be checked .( Determine whether it is a null pointer , Dereference of null pointers is not allowed )
- 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 ( Cast ).
- If parameters size by 0,malloc The standard is undefined , Depends on the compiler .
b.calloc
void* calloc (size_t num, size_t size);
The functionality :
- open up num Size is size A piece of space , And initialize each byte of the space to 0.
- And functions malloc The difference between : calloc Each byte of the requested space will be returned before the address is returned Initialize to full 0;
Still pay attention to judge null before using pointer !!!
c.realloc
void* realloc (void* ptr, size_t size);
The functionality :
Flexibly adjust the memory size , It can be big or small. ,“ Distribute on demand ”
explain :
ptr Is the memory address to be adjusted
size New size after adjustment
The return value is the starting memory position after adjustment .
On the basis of adjusting the size of the original memory space , The original data in memory will also be moved to “ new ” Space .
Be careful :
If there is enough space after the original space , Direct expansion , The original spatial data does not change
If there is not enough space after the original space , Find another space of appropriate size on the heap , And copy the original content to the new space , Release the original space
d.free
free(ptr);
ptr=NULL;
The functionality :
To put it bluntly, just one “ wipe ” Of ---- To free up memory
Release ptr Point to space , Often used with empty .
3. Classical written examination questions
Calibrated boldness , Think about function arguments , Formal parameter, actual parameter , Local variable life cycle , Knowledge of
problem : Is there a problem with the following code ?
No.1
- Investigate the function parameters , A formal parameter is a temporary copy of an argument
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
There is a problem , Cannot print hello world
reason :
GetMemory The function passes in a character pointer str, Even though p Points to a 100 Bytes of space , however Modification of the formal parameter does not change the argument , Yes str Come on : Space is not created ; Therefore, the copy cannot be completed ;
Correction method :
Address ;&str, Take the secondary pointer to receive
No.2
- Look at the life cycle of local variables
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
There is a problem , Can't print hello world
reason :
p When it comes back , The space pointed to has been destroyed , The life cycle of a local variable is only in its own {} Inside , It's out {}, Variables are destroyed , Which leads to str Became a wild pointer , Naturally, you can't print hello world
Correction method :
static modification , Let it have the properties of global variables , The following two can be
static char p[] = "hello world";
char static p[] = "hello world";
No.3
- Examine code writing habits
void GetMemory(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
//if(!str)
//return;
strcpy(str, "hello");
printf(str);
//free(str);
//str=NULL;
}
It can print hello, But the code is flawed : Did not judge whether the space was successfully opened , And there is no free, Memory leak
explain : The message is str The address of ,GetMemory() Pair of functions p To dereference , It changed str Point to space , It is equivalent to this time str It's no longer a NULL The pointer , Instead, a pointing size is 100 Pointer to a space of bytes ;
No.4
void Test(void)
{
char *str = (char *) malloc(100);
strcpy(str, "hello");
free(str);//
if(str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
This is obvious , The space has not been used yet free 了 , Even though str It's not a null pointer , But the space it points to is gone .
correct : Use first and then free, Leave it empty again . perfect !
4. Flexible array
be used for Structure , It is specified that the last element of the structure can be an array of unknown size , That is, flexible array . This can be combined with the dynamic memory allocation function , Flexible use of space ( Pile it up )
The following figure for C/C++ Memory region partition

Before the flexible array member in the structure Must at least There is another member .
sizeof The size of the structure returned does not include the memory of the flexible array .
Structures that contain flexible array members use malloc () Function to dynamically allocate memory , And the allocated memory should be larger than the size of the structure , To fit the expected size of the flexible array .
example : Storage of contact information in the address book applet
5. Examples of common dynamic memory errors
1. Dereference null pointer
Can cause error,so It is important for the pointer to determine whether it is a null pointer !!!
Determine null pointer method
if sentence ,assert// Assertion , The header file assert.h, coordination perror function , If the pointer is null , Output error messages directly
2. Cross boundary access to the space opened up by dynamic memory
seeing the name of a thing one thinks of its function , Access to a range outside the memory space , For example, pointer dereference , Array subscript access
3. Misuse free
The release of the Not Dynamic memory opens up space
Free dynamic memory allocation Part of the Space
such as :
void test()
{
int *p = (int *)malloc(100);
p++;
free(p);//p No longer points to the start of dynamic memory
}
4. Release the same space multiple times
“ Once is enough , Who can stand more ”
5. Forget to free up space
It's a bad habit , And the problem is serious , Can cause Memory leak . This space will not be released after use , Open up new space next time , in the course of time , You will find that there is no memory available ! Run under the usual compiler , Programmers can perform routine maintenance ; But few people maintain the program when it runs on the server , The consequences can be imagined .
边栏推荐
猜你喜欢

【C语言】动态内存管理

Project compilation nosuch*** error problem

Leetcode brush question diary sword finger offer II 053. Medium order successor in binary search tree

Leetcode 刷题日记 剑指 Offer II 048. 序列化与反序列化二叉树

What are the open earphones? Four types of air conduction earphones with excellent sound quality are recommended

NFT data storage blind box + mode system development

【二叉树基础知识】

RayMarching realizes volume light rendering

图形管线基础(二)

What is the best and most cost-effective open headset recommended
随机推荐
Development of clip arbitrage / brick carrying arbitrage system
Graphic pipeline foundation (part outside)
js 变量等于0也等也' '问题
Execjs call
C语言的动态内存管理函数
下雨场景效果(一)
2022-06-07 VI. log implementation
SSAO By Computer Shader(二)
[队列,栈的简单应用----包装机]
Leetcode 刷题日记 剑指 Offer II 050. 向下的路径节点之和
OJ 1020 minimum palindromes
Analysis of reentrantlock source code of AQS
OJ 1131 美丽数
Current learning progress
About the collation of shader keyword
OJ 1020 最小的回文数
AQS之CyclicBarrier源码解析
SSAO By Computer Shader(三)
mongoDB复制集及分片集群
redis实现分布式锁思路及redission分布式锁主流程分析