当前位置:网站首页>Dynamic memory management
Dynamic memory management
2022-07-04 09:47:00 【skeet follower】
Catalog
1. Why dynamic memory management exists
2. The introduction of dynamic memory function
3. Common dynamic memory errors
4.2 The characteristics of flexible arrays
4.3 The use of flexible arrays
4.4 Advantages of flexible arrays
1. Why dynamic memory management exists
Of course, we have mastered the way of memory development :
int a=10;// local variable - Four spaces are opened up in the stack space
int g_a=10;// Global variables - Static zone
But there are two characteristics of the way to open up space :
struct stu{
char name[20];
int age;
}
int main(){
int n=0;
scanf("%d",&n);
struct stu arr[n];
return 0;
}
Yes C99 This standard is introduced in , But many compilers do not support this standard , So it will report an error , Therefore, this method is not feasible .
2. The introduction of dynamic memory function
2.1malloc and free
Dynamic memory development function code example :
void* malloc (size_t size);
This function requests a piece of memory Continuously available Space , And return the pointer to this space .
- If the development is successful , Then return a pointer to open a good space .
- If the development fails , Returns a NULL The pointer , therefore malloc The return value of must be checked .
- The type of return value is void* , therefore malloc Function doesn't know the type of open space , Use yourself to decide when using .
void free (void* ptr);
free Function is used to release memory opened dynamically .
- If parameters ptr The pointed space is not opened dynamically , that free The behavior of a function is undefined .
- If parameters ptr yes NULL The pointer , Then the function does nothing .
#include<stdio.h>
#include<stdlib.h>
int main()
{
// Apply to memory 10 An integer space
int* p = (int*)malloc(10 * sizeof(int));//int* Force type to integer
if (p == NULL) {
// Failed to open up space , The reason for the printing error
printf("%s\n", strerror(errno));
}
else {
// Normal use space
int i = 0;
for (i = 0; i < 10; i++) {
*(p + i) = i;
}
for (i = 0; i < 10; i++) {
printf("%d", *(p + i));
}
}
// When dynamic memory space is not in use
// It should be returned to the operating system
free(p);
p = NULL;
return 0;
}
2.2calloc
calloc Function dynamic memory allocation . The prototype is as follows :
void* calloc (size_t num, size_t size);
- The function is for num Size is size The elements of open up a space , And initialize each byte of the space to 0.
- And functions malloc The only difference is calloc Initializes each byte of the requested space to full before returning the address 0. The code is as follows :

2.3realloc
- realloc Functions make dynamic memory management more flexible .
- Sometimes we find that the application space is too small in the past , Sometimes we think the application space is too large , That's for reasonable time memory , We will make flexible adjustments to the size of memory . that realloc Function can be used to adjust the dynamic memory size . The function prototype as follows :void* realloc (void* ptr, size_t size);
- ptr Is the memory address to be adjusted ,size New size after adjustment , The return value is the starting memory position after adjustment .
- This function adjusts the size of the original memory space , The original data in memory will also be moved to new Space .
#include<stdio.h>
#include<stdlib.h>
int main()
{
// Apply to memory 10 An integer space
int* p = (int*)malloc(20);//int* Force type to integer
if (p == NULL) {
// Failed to open up space , The reason for the printing error
printf("%s\n", strerror(errno));
}
else {
// Normal use space
int i = 0;
for (i = 0; i < 10; i++) {
*(p + i) = i;
}
}
int* ptr = realloc(p, 40);
if (ptr != NULL) {
p = ptr;
int i = 0;
for (i = 5; i < 10; i++) {
*(p + i) = i;
}
for (i = 0; i < 10; i++) {
printf("%d", *(p + i));
}
}
free(p);
p = NULL;
return 0;
}
3. Common dynamic memory errors
- Yes NULL Dereference operation of pointer
#include<stdio.h>
#include<stdlib.h>
int main()
{
int* p = (int*)malloc(40);
int i = 0;
for (i = 0; i < 10; i++)
{
*(p + i) = i;
}
free(p);
p = NULL;
return 0;
}
In case malloc Failed to open up space , be p Will be assigned a null pointer , therefore malloc When using, you must judge whether the return value is a null pointer .
- Cross border access to dynamic open space
#include<stdio.h>
#include<stdlib.h>
int main()
{
int* p = (int*)malloc(5 * sizeof(int));
if (p == NULL) {
return 0;
}
else {
int i = 0;
for (i = 0; i < 10; i++) {
*(p + i) = i;
}
}
free(p);
p = NULL;
return 0;
}
malloc Only opened up 5 An integer element , and for Loop access 10 Caused cross-border visits , Program crash .
- Use of non dynamic memory free Release
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a = 10;
int* p = &a;
*p = 20;
free(p);
return 0;
}
- Use free Release a piece of dynamic memory
#include<stdio.h>
#include<stdlib.h>
int main()
{
int* p = (int*)malloc(40);
if (p == NULL) {
return 0;
}
else {
int i = 0;
for (i = 0; i < 10; i++) {
*p++ = i;
}
}
free(p);
p = NULL;
return 0;
}
p Changes have taken place in this process , It is not our complete development space , If you want to release, you can only release it from the starting position of the opening , So wrong .
- Multiple releases of the same dynamic memory
void test()
{
int *p = (int *)malloc(100);
free(p);
free(p);// Repeat release
}
- Dynamic memory forget to release ( Memory leak )
void test()
{
int *p = (int *)malloc(100);
if(NULL != p)
{
*p = 20;
}
}
int main()
{
test();
while(1);
}
No space is released after use , Will continue to consume memory , It may cause the server to crash .
4. Flexible array
4.1 Concept of flexible array
Maybe you've never heard of Flexible array (flflexible array) The concept , But it does exist . C99 in , The most in the structureThe latter element is allowed to be an array of unknown size , This is called 『 Flexible array 』 member
The code is as follows :
typedef struct st_type
{
int i;
int a[];// Flexible array members
}type_a;
4.2 The characteristics of flexible arrays
- A flexible array member in a structure must be preceded by at least one other member .
- sizeof The size of the structure returned does not include the memory of the flexible array .
- Structures that contain flexible array members use malloc () Function to dynamically allocate memory , And the allocated memory should be larger than the size of the structure , Adapt to Expected size of the flexible array .

4.3 The use of flexible arrays
Code 1:
#include<stdio.h>
struct S {
int n;
int arr[0];
};
int main()
{
struct S* s = (struct S*)malloc(sizeof(struct S) + 5 * sizeof(int));
int i = 0;
for (i = 0; i < 5; i++) {
s->arr[i] = i;
}
struct S* ps = realloc(s, 44);
if (ps!= NULL) {
s = ps;
for (i = 5; i < 10; i++) {
s->arr[i] = i;
}
}
for (i = 0; i < 10; i++) {
printf("%d", s->arr[i]);
}
free(s);
s = NULL;
return 0;
}
Code 2:
#include<stdio.h>
struct S {
int n;
int* arr;
};
int main()
{
struct S* ps = (struct S*)malloc(sizeof(struct S) + 5 * sizeof(int));
ps->arr = malloc(5 * sizeof(int));
int i = 0;
for (i = 0; i < 5; i++) {
ps->arr[i] = i;
}
for (i = 0; i < 5; i++) {
printf("%d\n", ps->arr[i]);
}
int* ptr = realloc(ps->arr, 10 * sizeof(int));
if (ptr!= NULL) {
ps->arr = ptr;
for (i = 5; i < 10; i++) {
ps->arr[i] = i;
}
}
for (i = 0; i < 10; i++) {
printf("%d ", ps->arr[i]);
}
free(ps->arr);
free(ps);
ps = NULL;
return 0;
}
4.4 Advantages of flexible arrays
By comparing the above code 1 And code 2, Code 1 The implementation of has two benefits :
1. Convenient memory release
2. Conducive to access speed
边栏推荐
- Hands on deep learning (40) -- short and long term memory network (LSTM)
- In the case of easyUI DataGrid paging, click the small triangle icon in the header to reorder all the data in the database
- Go context 基本介绍
- Summary of the most comprehensive CTF web question ideas (updating)
- Golang 类型比较
- 智慧路灯杆水库区安全监测应用
- Ultimate bug finding method - two points
- 2022-2028 global optical transparency industry research and trend analysis report
- 2022-2028 global visual quality analyzer industry research and trend analysis report
- Kubernetes CNI 插件之Fabric
猜你喜欢
QTreeView+自定义Model实现示例
Summary of reasons for web side automation test failure
libmysqlclient.so.20: cannot open shared object file: No such file or directory
C # use ffmpeg for audio transcoding
Log cannot be recorded after log4net is deployed to the server
Hands on deep learning (40) -- short and long term memory network (LSTM)
SSM online examination system source code, database using mysql, online examination system, fully functional, randomly generated question bank, supporting a variety of question types, students, teache
SQL replying to comments
ASP. Net to access directory files outside the project website
Fabric of kubernetes CNI plug-in
随机推荐
Multilingual Wikipedia website source code development part II
Investment analysis and future production and marketing demand forecast report of China's paper industry Ⓥ 2022 ~ 2028
165 webmaster online toolbox website source code / hare online tool system v2.2.7 Chinese version
Histogram equalization
Solution to null JSON after serialization in golang
DR6018-CP01-wifi6-Qualcomm-IPQ6010-IPQ6018-FAMILY-2T2R-2.5G-ETH-port-CP01-802-11AX-MU-MIMO-OFDMA
Qtreeview+ custom model implementation example
Hands on deep learning (33) -- style transfer
Hands on deep learning (46) -- attention mechanism
[on February 11, 2022, the latest and most fully available script library collection of the whole network, a total of 23]
View CSDN personal resource download details
Write a jison parser from scratch (2/10): learn the correct posture of the parser generator parser generator
How to batch change file extensions in win10
Explanation of closures in golang
Launpad | Basics
Golang defer
Matlab tips (25) competitive neural network and SOM neural network
How can Huawei online match improve the success rate of player matching
Les différents modèles imbriqués de listview et Pageview avec les conseils de flutter
2022-2028 global special starch industry research and trend analysis report