当前位置:网站首页>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 :


边栏推荐
- Recruiting talents, gbase high-end talent recruitment in progress
- PostgreSQL: cannot change the type of column used by a view or rule
- Js继承方法
- MySQL怎么查询可以同时判断多个字段值是否存在
- Completion report of communication software development and Application
- GB/T 41479-2022信息安全技术 网络数据处理安全要求 导图概览
- [activity registration] User Group Xi'an - empowering enterprise growth with modern data architecture
- 站在大佬的肩膀上,你可以看的更远
- Alibaba technology has four sides + intersection +hr, and successfully got the offer. Can't double non undergraduate students enter the big factory?
- Data analysis interview question summary
猜你喜欢

c语言数组指针和指针数组辨析,浅析内存泄漏

Eight ways to solve EMC and EMI conducted interference

Data analysis interview question summary

Quickly build a gateway service, dynamic routing and authentication process, and watch the second meeting (including the flow chart)

Digital signatures and Ca certificates

Bash shell interaction free

Top all major platforms, 22 versions of interview core knowledge analysis notes, strong on the list

Customer first | domestic Bi leader, smart software completes round C financing

图片批处理|必备小技能

You're not still using xshell, are you? This open source terminal tool is yyds!
随机推荐
[soft test software evaluator] 2013 comprehensive knowledge over the years
Flink Window&Time 原理
Learn to draw with nature communications -- complex violin drawing
Mongodb (compare relational database, cloud database, common command line, tutorial)
oracle sql 问题
Redis basic knowledge, let's review it
Bluetooth technology | it is reported that apple, meta and other manufacturers will promote new wearable devices, and Bluetooth will help the development of intelligent wearable devices
说透缓存一致性与内存屏障
Gb/t 41479-2022 information security technology network data processing security requirements map overview
Digital signatures and Ca certificates
(13) Simple temperature alarm device based on 51 single chip microcomputer
When will brain like intelligence, which is popular in academia, land? Let's listen to what the industry masters say - qubits, colliders, x-knowledge Technology
Sentry log management system installation and use tutorial
Vrrp+mstp configuration details [Huawei ENSP experiment]
第2章-14 求整数段和
Go channel
Vk1620 temperature controller / smart meter LED digital display driver chip 3/4-wire interface with built-in RC oscillator to provide technical support
(IROS 2022) 基于事件相机的单目视觉惯性里程计 / Event-based Monocular Visual Inertial Odometry
Distributed system architecture theory and components
MDM数据质量应用说明