当前位置:网站首页>C language array pointer and pointer array discrimination, analysis of memory leakage
C language array pointer and pointer array discrimination, analysis of memory leakage
2022-07-28 09:00:00 【BSP primary school monk】
Blog home page :https://blog.csdn.net/weixin_46094737?type=blog
Feel free to leave a comment Please correct any mistakes !
This article was originally written by primary school student Lian , First appeared in CSDN
The future is long , It's worth our effort to go to a better life !

One 、 Memory leak
Use malloc()、calloc()、realloc() Dynamically allocated memory , If there is no pointer to him , You can't do anything , This memory will always be occupied by the program , Know that the program is recycled by the operating system after running .
Look at the following code :
#include <stdio.h>
#include <stdlib.h>
int main(){
char *p = (char*)malloc(100 * sizeof(char));
p = (char*)malloc(50 * sizeof(char));
free(p);
p = NULL;
return 0;
}1、 In this program , First assignment 100 Bytes of memory , And will p point at him ; Second distribution 50 Bytes of memory , Still used p point at him .
This leads to a problem , For the first time 100 There is no pointer to byte memory , And we don't know the address of this memory , So you can't get it back , There's no way to release , This memory becomes garbage memory , Although it's useless , But it still takes up resources , The only way is to wait for the program to run and recycle it by the operating system .
This is it. Memory leak , It can be understood as Program and memory lost contact , He can no longer be operated .
The metaphor of memory leak is “ The memory space available to all programs by the operating system is being squeezed out by a program ”, The end result is that the longer the program runs , Occupy more and more memory space , Finally use up all memory space , System crash .

2、 Let's look at a memory leak :
int *pOld = (int*) malloc( sizeof(int) );
int *pNew = (int*) malloc( sizeof(int) );These two lines of code create a block of memory respectively , And passed the memory address to the pointer pOld and pNew. Now the pointer pOld and pNew Point to these two pieces of memory respectively .
If you do this next :
pOld = pNew;
pOld The pointer points to pNew Memory address pointed to , At this time, release the memory :
free(pOld);
Released at this time pOld The memory space pointed to is the original pNew Point to the , So this space was released . however pOld The memory space originally pointed to has not been released , But because there is no pointer to this memory , So this memory is lost .

3、 in addition , You should not do something like this :
malloc( 100 * sizeof(int) );Such an operation is meaningless , Because there is no pointer to the allocated memory , Can't use , And they can't get through free() release , Caused a memory leak .
summary
free() The function is used to reclaim memory in real time , If the program is simple , It will not use too much memory before the end of the program , It doesn't degrade system performance , Then you can not write free() function . When the program is finished , The operating system frees memory .
But if you don't write when developing large programs free() function , The consequences are very serious . This is because it is likely to repeat the allocation 10000 times in the program 10M Of memory , If you use free() Function to release the exhausted memory space , Then the whole program only needs to use 10MB Memory can run . But if you don't use free() function , Then the program will use 100GB Of memory ! This includes most of the virtual memory , Because the operation of virtual memory needs to read and write disks , therefore , This will greatly affect the performance of the system , The system may therefore crash .
therefore , Use... In the program malloc() When allocating memory, write a corresponding free() Functions are a good programming habit . This can not only be reflected in the necessity of dealing with large programs , And can reflect to a certain extent The elegant style and robustness of the program .

Two 、 Pointer function array
seeing the name of a thing one thinks of its function , That is, every element is an array of function pointers , Add the array symbol directly after the function pointer name [ ] that will do .
The form of the statement :type (*func[ ])( parameter list )
C Language functions cannot be defined as arrays , You can only define function pointer arrays through function pointers .
#include <stdio.h>
int add(int x,int y)// Ordinary function
{
return x+y;
}
int sub(int x,int y)// Ordinary function
{
return x-y;
}
int cheng(int x,int y)// Ordinary function
{
return x*y;
}
int chu(int x,int y)// Ordinary function
{
return x/y;
}
int (*fun[4])(int,int)={add,sub,cheng,chu};// Function pointer array , Encapsulate function modules , By an array of function pointers (*fun[n]) Unified management
int main ()
{
int x,y;
char ch;
printf(" Please enter operator :\n");
ch=getchar();
switch(ch)
{
case '+':
printf(" Please enter two integers ( Space off , End of carriage return ):\n");
scanf("%d %d",&x,&y);
printf("%d+%d=%d",x,y,fun[0](x,y));
break;
case '-':
printf(" Please enter two integers ( Space off , End of carriage return ):\n");
scanf("%d %d",&x,&y);
printf("%d-%d=%d",x,y,fun[1](x,y));
break;
case '*':
printf(" Please enter two integers ( Space off , End of carriage return ):\n");
scanf("%d %d",&x,&y);
printf("%d*%d=%d",x,y,fun[2](x,y));
break;
case '/':
printf(" Please enter two integers ( Space off , End of carriage return ):\n");
scanf("%d %d",&x,&y);
printf("%d/%d=%d",x,y,fun[3](x,y));
break;
default:
break;
}
// fun = &add;
// printf("10 add 5 be equal to %d\n",fun(10,5));
// fun = ⊂
// printf("10 subtract 5 be equal to %d\n",fun(10,5));
// fun = &cheng;
// printf("10 multiply 5 be equal to %d\n",fun(10,5));
// fun = &chu;
// printf("10 except 5 be equal to %d",fun(10,5));
return 0;
}Running results :


Use condition limit 1 :
In a subfunction , You need to limit two integer formal parameter variables .
Use condition limit 2 :
The return value of the sub function needs to be an integer variable .
Array pointer and pointer array
1. Array pointer : Definition int (*p)[n];
because () High priority , First of all p It's a int Type a pointer , It points to an integer (int) One dimensional array of , The length of this one-dimensional array is n, It can also be said that there are n Lattice . Array pointers are also called pointers to one-dimensional arrays , Also called row pointer .
Array pointers can also be called “ Pointer to array ”, First, this variable is a pointer , secondly ,” Array ” Decorate this pointer , It means that this pointer stores the first address of an array , Or this pointer points to the first address of an array .
2. Pointer array : Definition int *p[n];
The array of pointers can be said to be ” An array of pointers ”, because *p There are no brackets , First, this variable is an array , secondly ,” The pointer p” Decorate this array , This means that all elements of this array are pointer types , The number of bytes occupied by the pointer is independent of its type , Only related to the system , stay 32 A system. , Pointers of any type occupy 4 Bytes , stay 64 A system. , Pointers of any type occupy 8 Bytes .

Example
Use a two-dimensional array pointer , Traverse and print a two-dimensional array
#include <stdio.h>
int main()
{
int i,j;
int arr[2][2]={
{20,30},{40,50,}};
int (*p)[2];// Define a two-dimensional array pointer
p=arr;// Pointer to the first address of the array
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf("arr[%d][%d]=%d ",i,j,*(*(p+i)+j));// Traverse and print all elements of the array
printf("\n");
}
return 0;
} Running results :

Use an array of pointers , Print a string of characters
#include <stdio.h>
int main()
{
int a=100;
printf("a The address for :%#p\n",&a);
char *name[2]={"hello","nihao"};// An array of pointers , Array name name
int i;
for(i=0;i<2;i++)
printf("%s ",name[i]);
printf("\n");
int *arr01[1]={&a};
printf(" The first address of the pointer array is :%#p\n",*arr01);
printf(" The value of the first address element of the pointer array is :%d",*arr01[0]);
return 0;
} Running results :


边栏推荐
- Redis basic knowledge, let's review it
- 1w5 words to introduce those technical solutions of distributed system in detail
- Explain cache consistency and memory barrier
- Why can ThreadLocal achieve thread isolation?
- How can MySQL query judge whether multiple field values exist at the same time
- 1299_ Task status and switching test in FreeRTOS
- Overview of head pose estimation
- PHP Basics - PHP uses PDO
- Quickly build a gateway service, dynamic routing and authentication process, and watch the second meeting (including the flow chart)
- Hundreds of billions of it operation and maintenance market has come to the era of speaking by "effect"
猜你喜欢
![Detailed explanation of switch link aggregation [Huawei ENSP]](/img/c2/f9797fe8b17a418466b60cc3dc50a1.png)
Detailed explanation of switch link aggregation [Huawei ENSP]

Why is the text box of Google material design not used?

快速搭建一个网关服务,动态路由、鉴权的流程,看完秒会(含流程图)

Line generation (matrix)

Competition: diabetes genetic risk detection challenge (iFLYTEK)

Vk1620 temperature controller / smart meter LED digital display driver chip 3/4-wire interface with built-in RC oscillator to provide technical support

Why setting application.targetframerate doesn't work

Chapter 2-14 sum integer segments

站在大佬的肩膀上,你可以看的更远

Learn to draw with nature communications -- complex violin drawing
随机推荐
ES查询索引字段的分词结果
Kubernetes cluster configuration DNS Service
JS手写函数之slice函数(彻底弄懂包头不包尾)
谷歌 Material Design 的文本框为什么没人用?
Quickly build a gateway service, dynamic routing and authentication process, and watch the second meeting (including the flow chart)
Completion report of communication software development and Application
Marketing play is changeable, and understanding the rules is the key!
KEGG通路的从属/注释信息如何获取
PostgreSQL queries [table field type] and [all series] in the library
Larkapi access credentials overview
Go waitgroup and defer
Ciou loss
Why can ThreadLocal achieve thread isolation?
1299_ Task status and switching test in FreeRTOS
看完这12个面试问题,新媒体运营岗位就是你的了
49 opencv deep analysis profile
[soft test software evaluator] 2013 comprehensive knowledge over the years
Analysis and recurrence of network security vulnerabilities
Why setting application.targetframerate doesn't work
Go panic and recover