当前位置:网站首页>Dynamic memory management and flexible array
Dynamic memory management and flexible array
2022-07-26 05:26:00 【Finally become master Kangkang】
Today I want to talk about dynamic memory development and flexible array .
Dynamic memory management :
Dynamic memory management mainly involves :malloc、calloc、realloc and free function . Mainly learn these four functions and apply them flexibly , Take the knowledge points in this aspect, even if you basically master , Don't say much now .
First of all malloc function :
void *malloc( size_t size );
malloc The type of void*, So before opening up dynamic memory, we need to think about the data type we want to create , And put malloc The type of is forcibly converted to the type we need . Its parameter is the number of bytes we need . Now let me give you an example , For example, we need to create 10 Integer data :

But the development of dynamic memory , If programmers do not recycle memory, memory leakage may occur , So how to reclaim the developed memory ? We need to use free function .
This is a free Declaration of functions :
void free( void *memblock );Very simple to use , The parameter is the address we dynamically open . notes : The opened memory address should finally be set as a null pointer .
free(str);
str = NULL;Now let's talk about it calloc function , It and malloc The difference is that it initializes the values in the memory development .
This is a calloc The initialization :
void *calloc( size_t num, size_t size );We still use to create 10 An example of plastic surgery :

The development of dynamic memory pays attention to dynamic , So how to achieve dynamic ?
This is a realloc Functions come in handy :
void *realloc( void *memblock, size_t size );
Now I want to create 10 An integer is extended to 20 A plastic , Use as follows :

Actually use realloc There are two ways for functions to open up memory :


Now let's talk about some common problems in dynamic memory development :
1. Space for non dynamic memory free Release .
2. use free Free some dynamic memory .
3. Make cross-border visits to dynamically opened spaces .
4. Yes NULL Pointer to dereference ( Whether the address opened is null Judgment of pointer )
5. Release the same dynamic memory multiple times .
6. The dynamic memory developed has not been released .
Now let's introduce some classic interview questions :
void GetMemory(char *p) {
p = (char *)malloc(100);
}
void Test(void) {
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}Please run Test What is the result of the function ?
1.str Spread GetMemory Want to receive p The address of , The known formal parameter is a temporary copy of the argument , Modification of a parameter does not affect the argument , so str It's still a null pointer ,strcpy take hello world Copy to null pointer to program error .
2. Dynamic memory development does not free space , Memory leak .
char *GetMemory(void) {
char p[] = "hello world";
return p; }
void Test(void) {
char *str = NULL;
str = GetMemory();
printf(str);
}Please run Test What is the result of the function ?
1.str Received dynamic memory development p The address of , But after the function comes out , because p The address occupying the stack space ,p Space will be reclaimed by the operating system , So lost access p The authority of space . Caused the use of wild pointer .
2. It won't print out hello world.
void GetMemory(char **p, int num) {
*p = (char *)malloc(num);
}
void Test(void) {
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}Please run Test What is the result of the function ?
1. Will print out the hello
2. Memory leak .
void Test(void) {
char *str = (char *) malloc(100);
strcpy(str, "hello");
free(str);
if(str != NULL)
{
strcpy(str, "world");
printf(str);
}
}Please run Test What is the result of the function ?
1. Space has been released before world Copying to the space pointed to by the pointer causes the problem of using wild pointers .
Modification method : take free In the last .
Flexible array :
typedef struct st_type
{
int i;
int a[];// Flexible array members
}type_a;The concept of flexible array is very simple , That is, the last structural variable in the structure is an array with uncertain size , We use it malloc Open up space for the structure ( The size of the opening is larger than the size of the structure to apply to the array ). The size of the structure is independent of the size of the array ( Array size is ignored ). There is at least one structure and other members in front of the array !
int i = 0;
type_a *p = (type_a*)malloc(sizeof(type_a)+100*sizeof(int));
// Business processing
p->i = 100;
for(i=0; i<100; i++) {
p->a[i] = i; }
free(p);Some people think that we can replace the array in the structure with a pointer , Open up a dynamic memory for this pointer . So here comes the question , Doing so will fragment memory , Secondly, it should be carried out twice free Release of space , Easy to cause memory leaks , Inconvenient for users . The last is to slow down the running speed : Every time you open up a space, you need to apply for permission from the operating system , Dynamic memory development will be carried out only after the operating system agrees .
So the advantages of flexible arrays are obvious !
Well, now I have sorted out the knowledge points of this chapter , If there is something wrong, please correct , Kangkang will accept it with an open mind !
边栏推荐
- Reason for pilot importerror: cannot import name 'pilot_ Version 'from' PIL ', how to install pilot < 7.0.0
- Attack and defense world flatscience
- Map making of environmental impact assessment based on remote sensing interpretation and GIS technology
- OD-Paper【2】:Fast R-CNN
- 《MongoDB入门教程》第08篇 比较运算符
- LeetCode链表问题——203.移除链表元素(一题一文学会链表)
- 第二讲 初识SLAM
- 开发项目事半功倍,一款开源的stm32驱动库大集合
- C language explanation series - understanding of functions (4) declaration and definition of functions, simple exercises
- Application of remote sensing, GIS and GPS technology in hydrology, meteorology, disasters, ecology, environment and health
猜你喜欢

Getaverse, a distant bridge to Web3

Improve reduce parallelism in shuffle operation

IVR在voip电话系统的应用与价值
C language explanation series -- understanding of functions (3) formal parameters, arguments, nested calls and chain access

MySQL optimization

TZC 1283: simple sorting - function method

SSTI payload and various bypass methods

No background, no education? Is it really hopeless for specialist testers to enter Internet factories?

Application of remote sensing, GIS and GPS technology in hydrology, meteorology, disasters, ecology, environment and health

SAP report development steps
随机推荐
开发转测试:从零开始的6年自动化之路
Thread三种实现方式 和 Handler的用法
Attack and defense world flatscience
测试必备工具之Fiddler,你真的了解吗?
Okaleido launched the fusion mining mode, which is the only way for Oka to verify the current output
IVR在voip电话系统的应用与价值
TZC 1283: simple sort - Comparative sort
高手是怎样炼成的?
又一开源神器,值得收藏学习!
MySQL optimization
Week 6 Learning Representation: Word Embedding (symbolic →numeric)
OD-Paper【2】:Fast R-CNN
MySQL master-slave synchronization and master-slave synchronization delay solution
C语言函数
Trend of the times - the rise of cloud native databases
TZC 1283: simple sort - select sort
高分子物理试题库
Common modules in ansible
NetCore MySql The user specified as a definer (‘admin‘@‘%‘) does not exist
Common solutions for distributed ID - take one