当前位置:网站首页>Advanced C language (XIII) - Example Analysis of dynamic memory management
Advanced C language (XIII) - Example Analysis of dynamic memory management
2022-07-25 08:01:00 【Not yet】
Catalog
Preface
This section mainly analyzes several examples , In order to slightly deepen the understanding of dynamic memory management .
1.
#include <stdio.h>
#include <stdlib.h>
void GetMemory(char* p){
p = (char*)malloc(100);
}
void Test(void){
char* str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
int main() {
Test();
return 0;
}

Result analysis
main()Function callTest()function , afterTest()Function callGetMemory()function .
Character pointer
strPassed in the functionGetMemory(),GetMemory()Function parameters are also character pointers , So character pointerstrIn fact, it is a value passing call , The message isstrValue . It is equivalent to creating a pointer with characters in the stack area of memorypReceived character pointerstrValueNULL.
stay
GetMemoeyInternal function , The pointerpYesmalloc()Function development 100 The starting position of a space of bytes .pThe starting address of the memory space is stored in . afterGetMemoryEnd of function call , And no value is returned , The pointerpBecause it is inGetMemory()Internal function , It's a local variable , thereforepThe memory block in which it is located is destroyed as the function call ends . herepThe space pointed to has not been releasedfree(), And because of the functionGetMemory()The call has ended without any pointer to this open space , It belongs to memory leakage .
go back to
Test()Continue to execute the program inside the function , At this time, due to the pointerpIs a pointerstrA temporary copy of , The pointerpNothing happens that affects the pointerstrValue , So character pointerstrThe value of the orNULL. Next functionstrcpy()Perform the operation : Put the string"hello world"Copy to pointerstrThe space it points to . howeverstrThe value of isNULL, The pointerstrIs a null pointer , There is no clear direction to , Copying will cause errors that cause the program to stop .
Correct or improve
#include <stdio.h>
#include <stdlib.h>
// Return the starting address of the dynamically opened space
char* GetMemory(){
char* p = (char*)malloc(100);
return p;
}
void Test(void){
char* str = NULL;
str = GetMemory();
strcpy(str, "hello world");
printf(str);
free(str);
str = NULL;
}
int main() {
Test();
return 0;
}
Running results :
2.
#include <stdio.h>
#include <stdlib.h>
char* GetMemory(void) {
char p[] = "hello world";
return p;
}
void Test(void) {
char* str = NULL;
str = GetMemory();
printf(str);
}
int main() {
Test();
return 0;
}
Running results :
Result analysis
main()Function callTest()function , afterTest()Function callGetMemory()function .
stay
GetMemory()Internal function ,p Is the name of the local character array , This array stores a string"hello world",GetMemory()Function returns the local character array name , That is, the address of the first element of the array .
stay
GetMemoryAfter the function ends the call, all its internal data is destroyed , Include local character arrays , Its memory area is reclaimed by the operating system ,Test()Character pointer in functionstrAccept the address of the memory area that has been reclaimed , sostrIt's a wild pointer , Points to the memory area that has been recycled that does not belong to this program . At this time, we don't know what is stored in this memory area , Of course, the output content is unknown .
Improve or correct
When defining a function, you can return the value of a local variable , This value can be received by external variables ; Do not return the address of a local variable , It doesn't make sense . It will also cause the pointer that accepts this address to become a wild pointer .
#include <stdio.h>
int* test() {
int a = 20;
return &a;
}
int main() {
int* p = test();
//printf("%d\n", 10);
printf("%d\n", *p);
return 0;
}
Running results :
#include <stdio.h>
int* test() {
int a = 20;
return &a;
}
int main() {
int* p = test();
printf("%d\n", 10);
printf("%d\n", *p);
return 0;
}
Running results :
Each call to a function will open up a function stack frame , After the function call is completed and returned, the stack frame is recycled by the operating system . After recycling , It is unknown whether the value stored in the reclaimed space is still the original value , If you open up a new function stack frame , Then it will cover the original recycled ( old ) Function stack frame .
3.
#include <stdio.h>
#include <stdlib.h>
void GetMemory(char** p, int num){
*p = (char*)malloc(num);
}
void Test(void){
char* str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
int main() {
Test();
return 0;
}
Running results :
Result analysis
main()Function callTest()function , afterTest()Function callGetMemory()function .
Test()Character pointer in functionstrAddress andinteger 100IntoGetMemory()function .GetMemory()Second level pointers are used for function parameterspAnd integersnumReceived correctly . After theGetMemory()Internal function , The secondary pointerpDereference once foundTest()First level pointer in functionstr, It's equivalent to a first level pointerstrreceivemalloc()The starting address of the allocated memory space . afterGetMemory()The function call ends and returns toTest()function .
The pointer
strWhat is stored in is the starting address of the dynamically opened memory .strcpy()Function to string"hello"Copy to pointerstrThe space it points to .printf()Function print pointerstrThe string pointed to . afterText()The function call ends and returns tomain(). aftermain()Function execution ends and returns0, Program end .
4.
#include <stdio.h>
#include <string.h>
void Test(void){
char* str = (char*)malloc(100);
strcpy(str, "hello");
//free After that, I didn't put the pointer str Set to null pointer ,str It's a wild pointer .
// Using wild pointers directly will cause problems .
free(str);
if (str != NULL){
strcpy(str, "world");
printf(str);
}
}
int main() {
Test();
return 0;
}
Result analysis
main()Function callText()function .
Test()Internal function , The pointerstrYesmalloc()The starting address of the allocated memory space . But there will bemalloc()Failure to allocate memory , here str Deposit isNULL. There should be rightstrWhether it isNULLThe inspection of .
strcpy()Function to string"hello"Copy to pointerstrThe memory space pointed to , afterfree()Function releases the pointerstrThe dynamically allocated memory space pointed to . Notice the following pointerstrIt's not set toNULL, The pointerstrIt also points to the starting address of the memory area that has been released . Now the pointerstrIt's a wild pointer . It's dangerous .
ifJudgestrWhether it is a null pointer , We have untilstrIt's not a null pointer , Points to the address of memory that does not belong to this program . If the judgment is true, perform the following operations :strcpy()The function will put the string"world"Copy to pointerstrThe space it points to , This operation is an illegal access to memory , Although the program can also output strings to the console , But this program also has problems .
Improve or correct
#include <stdio.h>
#include <string.h>
void Test(void){
char* str = (char*)malloc(100);
strcpy(str, "hello");
//
free(str);
str = NULL;
if (str != NULL){
strcpy(str, "world");
printf(str);
}
}
int main() {
Test();
return 0;
}
Conclusion
There may be obvious errors in the code related to dynamic memory management , This is certainly easy to correct . For example, receiving
malloc()、calloc()、realloc()Check the validity of the pointer to the starting address of the space 、 Release the dynamically opened memory space pointed to by the pointer and set the pointer toNULLetc. . There are also loopholes in writing logic that don't look good , We need to think and look for .
END
边栏推荐
- [QNX Hypervisor 2.2用户手册]9.3 cpu
- Supplementary notes on Relevant Issues of complete model group
- 转行学什么成为了一大部分人的难题,那么为什么很多人学习软件测试呢?
- Learn when playing No 1 | can live classroom still be like this? Come and unlock "new posture"!
- P1086 [noip2004 popularization group question 2] peanut picking
- 【ES6】函数的参数、Symbol数据类型、迭代器与生成器
- File details
- Tunnel broadcasting and wireless trunking communication broadcasting system - the case of Tiantaishan tunnel
- Uiautomator2 common commands
- 用一个栈实现另一个栈的排序
猜你喜欢

Didi - dispatching

Calculation formula of cross entropy

yolov7 网络架构深度解析

475-82(230、43、78、79、213、198、1143)

Vs2019 C MFC installation

交叉熵计算公式

Google AI can't understand the comments of netizens, and the wrong meaning will be as high as 30%. Netizens: you don't understand my stem

VS2019 C# MFC安装

Open source, innovators win, 2022 "science and innovation China" open source innovation list selection is fully open!

【Unity入门计划】基本概念-GameObject&Components
随机推荐
toolbar的使用
【Unity入门计划】基本概念-GameObject&Components
How to obtain the intersection / subtraction / Union of two sets by MySQL
机器学习理论及案例分析(part1)--机器学习基础
纳米数据足球数据,足球赛事比分,体育数据api,卡塔尔世界杯
[dynamic programming] - Knapsack model
In depth analysis of yolov7 network architecture
[unity entry program] make my first little game
People who lose weight should cry: it's no good not eating food, because your brain will be inflamed
设计一个有getMin功能的栈
P1047 [noip2005 popularization group t2] tree outside the school gate
滴滴 - dispatching
Learn when playing No 4 | can you take an online exam in programming? Right here →
机器学习入门详解(一):理解监督学习中的最大似然估计
P1047 [NOIP2005 普及组 T2] 校门外的树
[wechat applet] global style, local style, global configuration
[QNX hypervisor 2.2 user manual]9.3 CPU
Is the yield of financial products high or low?
7.24 simulation summary
uiautomator2 常用命令