当前位置:网站首页>Development of dynamic memory in C language
Development of dynamic memory in C language
2022-07-20 08:38:00 【This is iNEvitable】
Catalog
3. Introduction and use of library functions
·malloc and calloc Similarities and differences
· note
·realloc There are two situations when adjusting memory space
4. Common dynamic memory errors
5.C/C++ Program memory development
2. The characteristics of flexible arrays
3. Use and advantages of flexible arrays
· Advantages of flexible arrays
1. Preface
Dynamic memory is summarized as the memory that can be changed in our running program ,C Language provides malloc、calloc、realloc Library functions developed by dynamic memory , as well as Essential free Memory release function , They can make good use of memory , Even flexibly adjust the memory size , But there are also inevitable hidden dangers , But it can be eliminated .
Five memory partitions According to the memory address from high (0xffffffff) To low (0x00000000) The order of , Can be divided into 5 Big divisions : The stack area -> Heap area -> Global static area -> The constant area -> Code section .”
The development of dynamic memory is on the heap , Most of the local variables we usually use 、 Function parameters and other runtime allocation 、 The system automatically manages the stack area , So this may be a piece of knowledge for you to review the past and know the new , It may also be a fragment of knowledge that you know like the back of your hand , So I will make a brief summary 、 Easy to understand explanation 、 Go straight to the key details , How much will make you gain .
---------------------------------------------------------------------------------------------------------------------------------
2. Related header file
#include <stdio.h> /* printf, scanf, NULL */ #include <stdlib.h> /* malloc, realloc, calloc, free */
--------------------------------------------------------------------------------------
3. Introduction and use of library functions
First , Is the key library function malloc and calloc!
1.malloc frame
void* malloc (size_t size);
2.calloc frame
void* calloc (size_t num, size_t size);
---------------------------------------------------------------------------------------------------------------------------------
malloc and calloc Similarities and differences
1. The same thing
1. Unsigned shaping (size_t) and size The meaning of composition is the size of the memory to be opened , In bytes
2. Return value void* Indicates that it is applicable to all types of pointers to receive , And need Cast To adapt to the type pointer to be accepted
3. If It's a success , be Returns a pointer to the opened space .
If Failed to open up , be Return to one NULL The pointer , therefore malloc、calloc as well as realloc The return value of must be checked ( For example, set a pointer to store the returned address , Judge whether it is NULL, If not for NULL, Then use the pointer to be used to store , In this way, you can avoid changing the pointer value you want to use ).
4. If Parameters size by 0, The standard is Undefined Of , Depends on the compiler .
---------------------------------------------------------------------------------------------------------------------------------
2. Difference
1.malloc The opened space is uninitialized ,calloc Default initialization is 0, The unit is byte
2.calloc in num Parameter indicates to open num individual size Bytes of size , such as calloc(3,4); Means to open up 3 Size is 4 A block of memory in bytes , Can be used in an array
3. Compared with malloc,calloc Initialization of appears to be better , Suggestions for use are calloc
---------------------------------------------------------------------------------------------------------------------------------
3.free frame
void free (void* ptr);
a key !free,free,free! Reuse malloc A series of dynamic memory development related library functions are certain ! A certain ! We must cooperate with free To use !
---------------------------------------------------------------------------------------------------------------------------------
4.malloc Use
To sum up, let's try some code ( Very important , Combine theory with practice )~~~ To sum up, let's try some code ( Very important , Combine theory with practice )~~~
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr = (int*)malloc(40);
// Because here we only do demonstrations , For valuable pointers, you need to open a new pointer to store and judge, and then
//malloc Open up the pointer into this valuable pointer
if (ptr == NULL)
{
perror("malloc");
// perhaps printf("%s",strerror(errno)); however strerror The header file is string.h errno The header file is errno.h
// You can also see that perror It's simpler and more convenient , you 're right , Its use is to print on the terminal "" What's in double quotation marks + One : The colon + error message
// Print directly using perror, If you only want the error code, use strerror(errno), because error Stored is the error code of the program ,
//strerror Is to convert the error code into a string , Don't to %s Printing in the form of a string is equivalent to getting a pointer , Point to this error message .
return 1;
// Set return value , Prevent continued execution , This is essential .
}
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", *(ptr + i));
}
// Essential after use free and NULL empty
free(ptr);
ptr = NULL;
return 0;
}
note
Among them, the knowledge points :perror、strerror Related to error code
It's easy to get wrong : Forget to judge NULL, forget free And null pointer
free Release ( Return ) Space , But it will not be set as a null pointer , Prevent it from being a wild pointer 、 Prevent memory leaks ( no need , Occupancy space ), It needs to be set to null pointer manually , So remember The library function to open up heap space should be the same as free Use it together
Expand :free The memory space can be automatically reclaimed without releasing and waiting for the program to end
5.calloc Use
#include <string.h>
#include <errno.h>
int main()
{
int* ptr = calloc(10, 4);
if (ptr == NULL)
{
printf("%s", strerror(errno));
return 1;
}
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", *(ptr + i));
}
free(ptr);
ptr = NULL;
return 0;
}
--------------------------------------------------------------------------------------------------------------------------------- secondly , It's the play realloc, This is a heavyweight
6.realloc frame
void* realloc (void* ptr, size_t size);
1.ptr Is the memory address to be adjusted
2.size New size after adjustment
3. The return value is the starting memory position after adjustment .
7.realloc Use
Code can't stop , Feel its usefulness
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* p = (int*)calloc(10, sizeof(int));
if (p == NULL)
{
perror("calloc");
return 1;
}
//realloc The newly allocated size is 20 Bytes
int* ptr = (int*)realloc(p, 20 * sizeof(int));
if (ptr != NULL)
{
p = ptr;
}
//free Release
free(p);
p = NULL;
return 0;
}
realloc Adjusting memory space There are two situations
1. The original space has enough space ;
2. The original space is not large enough .
To sum up :realloc Open up space , When there is enough space in the back, the original initial address is still used , Capacity expansion ( Add directly ), Insufficient space , Will open up a new space , Find a continuous space at a time , Copy the original content to the new address , At this time, the address changes , If you can't find the right space to resize , At this time, the null pointer is returned , So the original pointer variable is not used to receive the value , Prevent the value from being changed
---------------------------------------------------------------------------------------------------------------------------------
4. Common dynamic memory errors
Here are two strings of code to taste
// Dynamic memory forgets to release 、 Memory leak
int main()
{
int* p = (int*)malloc(100);
int flag = 0;
scanf("%d", &flag);//5
if (flag == 5)
return 1;//!!!
free(p);
p = NULL;
return 0;
}
int* test()
{
int* p = (int*)malloc(100);
if (p == NULL)
{
return p;//1. Avoid dereferencing null pointers
}
return p;
}
int main()
{
int* ret = test();
// Forget to release the opened dynamic memory
return 0;
}
5.C/C++ Program memory development

C/C++ Several areas of program memory allocation
1. The stack area (stack): When executing a function , The memory units of local variables in the function can be created on the stack , The function executes the knot
These storage units are automatically released when the beam is loaded . Stack memory allocation operations are built into the processor's instruction set , It's very efficient , however
The memory allocated is limited . The stack area mainly stores the local variables allocated by running functions 、 Function parameter 、 Return the data 、 return
Return address, etc .
2. Heap area (heap): Release is usually assigned by the programmer , If programmers don't release , At the end of the program, the OS Recycling . branch
The matching method is similar to a linked list .
3. Data segment ( Static zone )(static) Store global variables 、 Static data . Released by the system at the end of the program .
4. Code segment : Store function body ( Class member functions and global functions ) The binary code of .
With this picture , We can better understand in 《C First knowledge of language 》 As mentioned in static Keywords modify local variables .
In fact, ordinary local variables allocate space in the stack area , The characteristic of stack area is that the variables created above are destroyed when they are out of scope .
But be static The modified variables are stored in the data section ( Static zone ), Data segments are characterized by variables created above , Until the program
Destroy only when it's over , So the life cycle gets longer .
6. Flexible array
1. Concept of flexible array
C99 in , The last element in the structure is allowed to be an array of unknown size , This is called 『 Flexible array 』 member
Using flexible arrays can flexibly open up the dynamic memory size of complex objects , Allocate memory effectively and reasonably , This is related to dynamic memory , So it can't be avoided free Release the pointer of dynamic memory development and manually set it to NULL Null pointer .
2. The characteristics of flexible arrays
1. The last member in the structure is an array , The number of array elements is empty or 0.
2. Flexible array members in structure Must be preceded by at least one other member .
3.sizeof The size of the structure returned does not include the memory of the flexible array .
4. 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 , To fit the expected size of the flexible array .
3. Use and advantages of flexible arrays
Code 1 Is the use of flexible arrays
Struct S
{
int i;
int arr[0];
}
int main()
{
int i = 0;
S* p = (S*)malloc(sizeof(S) + 100 * sizeof(int));
p->i = 100;
for (i = 0; i < 100; i++)
{
p->arr[i] = i;
}
free(p);
return 0;
}
Code 2 Is a pointer to dynamic memory development
typedef struct S
{
int i;
int* i2;
}S;
int main()
{
S* p = (S*)malloc(sizeof(S));
p->i = 100;
p->i2 = (int*)malloc(p->i * sizeof(int));
int i = 0;
for (i = 0; i < 100; i++)
{
p->i2[i] = i;
}
// Release space
free(p->i2);
p->i2 = NULL;
free(p);
p = NULL;
return 0;
}
Advantages of flexible arrays
Code 1 Are the benefits of Convenient memory release , Allocate memory once , For example, user use code 2 I don't know it needs to be released twice , Code 1 The user does it once free You can free up all the memory . secondly , yes It is helpful to improve the access speed , Because the development of memory is continuous , also It is beneficial to reduce memory fragmentation ( Some memory not used ).
边栏推荐
- 15.内置指令
- 进程与线程以及进线程间通信
- 淘宝flexible.js文件实现弹性布局
- Pytorch target detection data processing (II) extracting difficult samples, low AP samples
- 77-全局自定义指令
- Pytorch target detection coco API explanation data generation
- 学生成绩管理系统(c语言)
- [Day.2]约瑟夫环问题,如何用数组代替循环链表(详解)
- 基数排序(桶排序)
- Explain the full permutation problem in detail (different output results of different solutions)
猜你喜欢
随机推荐
Character functions and string functions
C language program environment and preprocessing
数据的表示和运算
C语言实现通讯录
100-京东导航栏-插槽使用-弹性布局(display: flex;)
数据在内存中的存储
shell脚本编程
JS如何判断当前日期是否在某个范围内
Recursive backtracking - maze walking
动态内存申请
二阶及N阶最长公共子序列
Easier to use C language entry-level cheese (2) select statements + loop statements, functions, arrays, operators (super detailed)
Study diary - pointer topic
C语言结构体类型
scroll案例:带有动画的返回顶部
Learning diary 6 array
学习日记3-数据的输入输出
[调试bug]JS:getFullYear is not a function
淘宝flexible.js文件实现弹性布局
递归回溯—走迷宫