当前位置:网站首页>Explain C language dynamic memory management in detail
Explain C language dynamic memory management in detail
2022-07-19 14:31:00 【Finally - null】
Make a little progress every day , Persistence makes a big difference !!!

Preface :
stay C In the process of language learning, for the storage of variables in memory, you first need to apply for space from memory , Sometimes we can't decide how much space to apply for at one time , This requires us to use memory more flexibly , When there is not enough memory to apply for at the beginning, you can continue to apply for space on the original basis
1. The introduction of dynamic memory function :
1.malloc
#include<stdlib.h>
void* malloc (size_t size);
Apply to this function for memory One piece continuously available Space , And return the pointer to this space .
The rules for using functions :
If the development is successful , Then return a pointer to open a good space ;
If the development fails , Returns a NULL The pointer ;
The return value is void*, Therefore, it is necessary to use type forced conversion according to the actual situation ;
If size The value of is 0, Then the standard is undefined , Depends on the compiler .
2.free
void free (void* ptr);
Used for dynamic memory release and recycling
The rules for using functions :
If parameters ptr The pointed space is not opened dynamically , that free The behavior of a function is undefined
If ptr yes NULL The pointer , Then the function does nothing
3.calloc
void* calloc (size_t num, size_t size);
The rules for using functions :
by num Size is size The elements of open up a continuous space , And put the space Each byte is initialized to 0;
And malloc The function is different in that it initializes each byte of the requested space as 0, Everything else is the same
4.realloc
void* realloc (void* ptr, size_t size);
You can flexibly adjust the memory size
Function usage rules :
ptr Is to adjust the starting position of memory ;
szie Is the adjusted total size ;
The return value is the starting position of the memory after adjustment .
realloc There are two ways to adjust memory :
situation 1: Continue to add space to the original space , The original spatial data does not change
situation 2: When you continue to add space to the original space , There is not enough space for follow-up , So I will find a new space in memory , And will put the original data copy into the newly applied space .
2. Common dynamic memory errors :
1. Yes NULL Pointer to dereference :
int* p = (int*)malloc(8000); *p = 20; free(p); p = NULL;
2. Cross border access to dynamically opened memory :
int* p = (int*)malloc(40); if (p == NULL) { printf("%s\n", strerror(errno)); } int i = 0; for (i = 0; i <= 10; i++) { *(p + i) = i; } for (i = 0; i <= 10; i++) { printf("%d ", *(p + i)); } free(p); p = NULL;
3. For non dynamically opened memory free Release :
int a = 10; int* p = &a; free(p); p = NULL;
4. Use free Release part of the space opened dynamically :
int* p = (int*)malloc(40); if (p == NULL) { printf("%s\n", strerror(errno)); } int i = 0; for (i = 0; i < 5; i++) { *p = i; p++; } free(p); p = NULL;
5. Release the same dynamic memory multiple times :
int* p = (int*)malloc(50); free(p); //…… free(p);
6. Dynamic development of memory forget to release ( Memory leak ):
void test() { int* p = (int*)malloc(40); if (p != NULL) { *p = 10; } } int main() { test(); return 0; }test After the function is called , The function stack frame is returned to the operating system , however p The dynamic development memory originally pointed to has not been released .
3. Classic written test questions about dynamically opening up memory :
1. Topic 1 :
test What will be the result of function operation ?
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; }
modify :
2. Topic two :
char* GetMemory(void) { char p[] = "hello world"; return p; } void test(void) { char* str = NULL; str = GetMemory(); printf(str); } int main() { test(); return 0; }
3. Topic three :
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; }
modify :
4. Topic four :
void test(void) { char* str = (char*)malloc(100); strcpy(str, "hello"); free(str); if(str!=NULL) { strcpy(str, "world"); printf(str); } } int main() { test(); return 0; }
modify :
4. Flexible array :
1. Concept :
The last element in the structure can be an array of unknown size , This is called a flexible array .
2. The characteristics of flexible arrays :
1. The flexible array member in the structure is preceded by at least one other member ;
2.sizeof The returned structure size does not include the size of the flexible array ;
3. The structure containing the members of a flexible array is malloc Function to dynamically allocate memory , And the allocated size should be larger than the total size of the structure , Adapted to the size of the flexible array ;
3. Advantages of flexible arrays :
The above structure can also be designed as the following code :
![]()
Compare the advantages of flexible arrays with each other :
1. Facilitate the release of memory :
The flexible array only needs to be released once to release memory , It greatly reduces the problem of forgetting to release dynamic memory2. Conducive to access speed :
It is beneficial to improve the access speed , It also helps reduce memory fragmentation
summary :
So that's about C Detailed explanation of knowledge points of language dynamic memory development , I hope I can help each other in the process of learning , Promote each other , Welcome to like , Leave a comment !!!
边栏推荐
- Optimizer of pytoch framework optimizer
- 单片机软件定时器V2.0
- Redis源码与设计剖析 -- 4.跳跃表
- Installation of Topy Library (topology optimization software)
- SQL相关的时间日期类型
- The manual is not complete. How to manually dig out the monitoring information of tongweb?
- Code runner for vs code, with more than 40million downloads! Support more than 50 languages
- 00 后博士获聘南大特任副研究员,曾 4 岁上小学,14 岁考入南大!
- Event preview | Apache Doris x Apache seatunnel joint meetup to start registration!
- 暑期rhcsa培训第三天作业
猜你喜欢

MVCC多版本并发控制

How to avoid global index in pychart? How to cancel the indexing of a folder?

Comprehensive analysis of C language multimedia open source framework GStreamer

揭开服务网格~Istio Service Mesh神秘的面纱

Cmake learning notes

详解C语言动态内存管理

贝塞尔曲线简单介绍

Huawei technologies:jonathan Krolikowski | from design to deployment, zero contact deep reinforcement learning WLANs

C - usage of this

Addition, deletion, modification and query of database
随机推荐
Code Runner for VS Code,下载量突破 4000 万!支持超过50种语言
非凸优化问题经典必看综述“从对称性到几何性”,罗切斯特大学等
JSON path syntax introduction and usage scenarios
Addition, deletion, modification and query of database
通达信开户是真的吗?通达信开户安全吗?
Huawei Technologies:Jonatan Krolikowski | 从设计到部署零接触深度强化学习WLANs
函数初认识-下
华为无线设备配置动态负载均衡
STM32 positioning hardfault location method and encountered situation in keil environment
[acwing] solution of the 60th weekly match
华为无线设备配置智能漫游
华为无线设备配置静态负载均衡
CF 807 E. mark and Professor Koro (weight segment tree)
After 2000, he was hired as a special associate researcher of Nanjing University. He went to primary school at the age of 4 and was admitted to Nanjing University at the age of 14!
AcWing 274. Mobile services [DP]
Win10 Microsoft Store cannot be opened (enable TLS 1.2)
Unveil the mystery of service grid istio service mesh
Some puzzles about data dictionary
Okaleido or get out of the NFT siege, are you optimistic about it?
Cmake learning notes























