当前位置:网站首页>[C language note sharing] - dynamic memory management malloc, free, calloc, realloc, flexible array
[C language note sharing] - dynamic memory management malloc, free, calloc, realloc, flexible array
2022-07-28 17:45:00 【Crazy orange】
List of articles
- 1. Why is there dynamic memory allocation
- 2. Dynamic memory function introduction
- 3. Common dynamic memory errors
- 3.1 Yes NULL Dereference operation of pointer
- 3.2 Cross border access to dynamic open space
- 3.3 Use of non dynamic memory `free` Release
- 3.4 Use `free` Release a piece of dynamically opened memory ` Part of the `
- 3.5 For the same dynamic memory ` Multiple releases `
- 3.6 Dynamic memory ` Forget to release `( Memory leak )
- 4. Classic written test questions
- 5. C/C++ Program memory development
- 6. Flexible array
1. Why is there dynamic memory allocation
int val = 20;// Open up on the stack space 4 Bytes
char arr[10]={
0};// Open up on the stack space 10 Bytes of contiguous space
- The way the above code opens up space has two characteristics :
- The size of the space is fixed .
- When an array is declared , You must specify the length of the array , The memory it needs is allocated at compile time .
- The need for space , Not only the above situation , Sometimes the required space size can only be known when the program is running , The way arrays open up space at compile time is not enough .
2. Dynamic memory function introduction
notes : All dynamically developed spaces are developed in the stack area !

2.1 malloc and free
- malloc and free It's all stated that
stdlib.hHeader file .
2.1.1 malloc Use
malloc( Function link )
void* malloc (size_t size);
- If the development is successful , Then return a pointer to open a good space .
- If the development fails , Returns a
NULLThe pointer , thereforemallocThe return value of must be checked ! - The type of return value is
void*, thereforemallocFunction doesn't know the type of open space , The specific time of use is determined by the user himself . - If parameters
sizeby0,mallocThe standard of behavior is undefined , Depends on the compiler .( open up 0 Byte space doesn't mean it's wrong ) - Frequent use
mallocOpening up space will lead to memory fragmentation
- [ ] effect : Apply for a piece of memory
Continuously available space, And return the... Pointing to this spaceThe pointer.
- Example :

2.1.2 free Use
free( Function link )
void free (void* ptr);
If parameters
ptrThe pointed space is not opened dynamically , thatfreeThe behavior of a function is undefined .( It does not mean that only dynamically opened memory can be released )If parameters
ptryesNULLThe pointer , Then the function does nothingFor the same space , Several times
freeRelease , There's no mistake , But it is recommended not to release multiple timeseffect : Used to free up dynamically opened memory .
- Example :

- Example :
2.2 calloc
calloc( Function link )
void* calloc (size_t num, size_t size);
callocIt is also used for dynamic memory allocation .- And functions
mallocThe only difference iscallocEach byte of the requested space will be returned before the address is returned Initialize to full 0.
- [ ] effect : by
numSize issizeThe elements of open up a space , And initialize each byte of the space to0.
- Example :

2.3 realloc
realloc( Function link )
void* realloc (void* ptr, size_t size);
reallocFunctions make dynamic memory management more flexible .reallocFunction can be used to adjust the size of dynamic development memory ( Expand memory , Reduce memory )ptrIs the memory address to be adjusted .sizeAdjusted new size- The return value is the starting memory position after adjustment .
- This function adjusts the size of the original memory space , The original data in memory will also be moved to
newSpace . - In the use of
reallocWhen adding memory , Do not use the originalPointer variable receiving (ptr), Need to createNew pointer variablereceive , preventreallocFailed to apply for space , Lead toThe original pointer (ptr)byNull pointer reallocThere are two ways to adjust memory space :
situation 1. There is enough space behind the original space
situation 2. There is not enough space after the original space

situation 1: When it's the case 1 When , To expand memory, 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 space ,
The way to expand is : In the heap space to find another suitable size of continuous space to use . In this way, the function returns a new memory address .
- Example :

Capacity expansion , Address
Probablychange , Compare the following three screenshots
Here aresituation 2:
When there is not enough space after the original space ,
In the heap space to find another suitable size of continuous space to use . In this way, the function returns a new memory address .



3. Common dynamic memory errors
3.1 Yes NULL Dereference operation of pointer

3.2 Cross border access to dynamic open space

3.3 Use of non dynamic memory free Release

3.4 Use free Release a piece of dynamically opened memory Part of the
To release the dynamically opened space, you must release it from the starting address , It is impossible to release only part of the memory !

3.5 For the same dynamic memory Multiple releases

3.6 Dynamic memory Forget to release ( Memory leak )

Forgetting to free the dynamically opened space that is no longer used will cause a memory leak .
Bear in mind : The space opened up dynamically must be released , And release it properly
4. Classic written test questions
- Example :
printf(str);==printf("abcd");
Is equivalent tostrThe first address was given toprintf
char* p ="abcd";//p It's just a The address of
printf(p);

- 1. Correct modification : Address transmission

- 2. Correct modification : Function return value

5. C/C++ Program memory development

C/C++ Several areas of program memory allocation :
- The stack area (stack): When executing a function , The memory units of local variables in the function can be created on the stack , At the end of the function execution, these storage units Automatically released . Stack memory allocation operations are built into the processor's instruction set , It's very efficient , But the allocated memory capacity is limited . The stack area is mainly used to store the... Allocated by running the function
local variable 、 Function parameter 、 Return the data 、 The return addressetc. . - Heap area (heap): Release is usually assigned by the programmer , If programmers don't release , At the end of the program, the OS Recycling . The distribution method is similar to
Linked list. Depositmalloc、realloc、callocOpen up space andfree. - Data segment ( Static zone static): Deposit
Global variables 、 Static data. Released by the system at the end of the program . - Code block : Deposit
The body of the function ( Class member functions and global functions )The binary code of
6. Flexible array
Maybe you've never heard of flexible arrays (flexible array) The concept , But it does exist .
C99 in , The last element in the structure is allowed to be an array of unknown size , This is called 『 Flexible array 』 member .
for example :
- Some compilers will report errors and cannot compile , You can change to :

6.1 The characteristics of flexible arrays
- The flexible array member of structure red must be preceded by at least one other member .
sizeofThe 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 shouldLarger than the size of the structure, To fit the expected size of the flexible array
for example :

6.2 The use of flexible arrays
Flexible array scheme : once
free、malloc
So flexible array members a, It's equivalent to getting 100 A continuous space of two shaping elements . If you feel
mallocThe space opened up is small , You can usereallocResize .

6.3 The advantages of flexible arrays
No Flexible array scheme :2 Time
free、malloc, secondlymallocThe more you use ,Memory fragmentsThe more possibilities

1. The first advantage is : Convenient memory release
If our code is really a function for others , You do a secondary memory allocation in it , And return the whole structure to the user . The user calls
freeYou can release the structure , But the user doesn't know that this structure member mayfree, So you can't expect users to find out . therefore , If we allocate the memory of the structure and its members at one time , And return a structure pointer to the user , Users oncefreeYou can also free up all the memory .
2. The second advantage is : This is good for access speed .
Continuous memory is good for improving access speed , It also helps reduce memory fragmentation .( Actually , Personally, I don't think it's much higher , Anyway, if you can't run, you need to add offset to address )
Extended reading ( Hyperlinks )
C Arrays and pointers in language structures
边栏推荐
猜你喜欢

MySQL optimization summary

Technical aspects passed easily, HR: those with only three years of experience in large factories are not worth 20K

Mysql 优化总结

Can‘t use an undefined value as an ARRAY reference at probe2symbol

Mmcv installation method

.net动态调用webservice的三种方式

In depth sharing of Ali (ant financial) technical interview process, with preliminary preparation and learning direction

【 R语言—基础绘图】

点云处理---二叉树

mmdetection3d(2)---结果、log可视化
随机推荐
[untitled]
Adding new objects to the object array in JS results in the modification of existing objects in the array
软件测试前景如何?该如何进行学习呢?
leetcode系统性刷题(一)-----链表、栈、队列、堆
软件测试干货
.net MVC understanding
ROS零散知识点及错误解决
QT编写串口助手
Sql Server STUFF与FOR XML PATH
软件测试培训需要多久?
转行学习软件测试有前途吗?
MySQL与IDEA连接
解决Package is not available (for R ve【PACKAGE ‘XXX’ IS NOT AVAILABLE (FOR R VERSION X.Y.Z)” WARNING?】
软件测试培训两个月靠谱吗?
easyui tree
想转行IT,非科班出身真的不要紧吗?
Convert the image file of input type='file'to Base64
软件测试的培训机构靠谱吗
Database optimization -- deeply understand the underlying data structure and algorithm of MySQL index
新人如何入门学习软件测试