当前位置:网站首页>C language - dynamic memory management
C language - dynamic memory management
2022-07-27 06:23:00 【Autumn mountain chariot God AE】
Dynamic memory exploit function malloc And dynamic memory release function free:
void* malloc (size_t size);Use malloc When opening up space , Need to pass a size_t Type as the size of the memory space to be opened ( In bytes )
malloc The letter will return a void* Pointer to type , Point to the starting position of the opened space
If the development fails , Return null pointer NULL( So check it after returning .)
Pay attention to , After opening up, you need to save the starting address of the return ,
After using the space , Need to use free Function to free up the space , Otherwise, it will cause memory leakage .
void free (void* ptr);If the starting location address is not saved , Then the space cannot be released .
free Function cannot free the space opened up by non dynamic memory ,free Function cannot release part of the dynamic memory opening space .
If the incoming free Function is null pointer , So the function doesn't do anything .
free Function is actually changing the operation right of memory space to the operating system , Change space may still exist , But if free After that, I still keep the address of the space , This address is the wild pointer , In order to avoid the travel of wild pointer , We are free After that, set the pointer to NULL.
free(p);
p=NULL;calloc function :
calloc Function can dynamically open up a block with the number of elements num, The size of each element is size Of memory space , And initialize the values of all elements to 0. The rest and malloc identical .
void *calloc(size_t num,size_t size);realloc function :
realloc Function is to expand the opened dynamic memory space
Pass in realloc Function is the starting address of the dynamic memory space that needs to be adjusted , And the adjusted new space size
void* realloc (void* ptr, size_t size);If there is enough space to expand after the starting position , Then the original address will be returned after the expansion ;
If there is not enough space to expand after the starting position , that realloc Function will find a suitable location in memory space , Move the contents of the original space to the new space , And return the actual address of the new space ; If the expansion fails , Then return to NULL.
Some common errors in dynamic memory development
1. For those who fail to open up NULL Pointer to dereference :
void test()
{
int *p = (int *)malloc(INT_MAX/4);
*p = 20;// If p The value of is NULL, There will be problems
free(p);
}Therefore, before dereferencing the returned address, you should first determine whether it is a null pointer .
2. Cross border access to dynamic open space
void test()
{
int i = 0;
int *p = (int *)malloc(10*sizeof(int));
if(NULL == p)
{
exit(EXIT_FAILURE);
}
for(i=0; i<=10; i++)
{
*(p+i) = i;// When i yes 10 Cross border visits when
}
free(p);
}During operation, check to prevent cross-border access .
3. Use of non dynamic memory free Release
void test()
{
int a = 10;
int *p = &a;
free(p);//ok?
}
4 Use free Release a piece of dynamic memory
void test()
{
int *p = (int *)malloc(100);
p++;
free(p);//p No longer points to the start of dynamic memory
}
5. Multiple releases of the same dynamic memory
void test()
{
int *p = (int *)malloc(100);
free(p);
free(p);// Repeat release
}
6. Dynamic memory forget to release ( Memory leak )
void test()
{
int *p = (int *)malloc(100);
if(NULL != p)
{
*p = 20;
}
}
int main()
{
test();
while(1);
}So we should release memory , And release the memory correctly .
Several common written examination questions
void GetMemory(char *p) {
p = (char *)malloc(100);
}
void Test(void) {
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}analysis : Pass in getmemory The formal parameter of a function is a pair of real parameters str A temporary copy of , Operations on formal parameters within functions do not affect str, So the correct way is to take str The address of is passed into the function , In this way, dereference of formal parameters in the function can operate to str.
char *GetMemory(void) {
char p[] = "hello world";
return p; }
void Test(void) {
char *str = NULL;
str = GetMemory();
printf(str);
}analysis :getmemory String constants in function p Stored in the stack , Although the address of the first element of the string was passed in str; But the call to the function ends , This space is destroyed ,str The address stored in becomes a wild pointer , Dereference of wild pointers is naturally not possible .
void GetMemory(char **p, int num) {
*p = (char *)malloc(num);
}
void Test(void) {
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}analysis :getmemory Functions and str No problem The real problem is that there is no space for dynamic memory after use free operation .
void Test(void) {
char *str = (char *) malloc(100);
strcpy(str, "hello");
free(str);
if(str != NULL)
{
strcpy(str, "world");
printf(str);
}
}analysis :free Not later str Set as NULL, Lead to str Become a wild pointer , Understand and reference the wild pointer .
Yes str Is it NULL The judgment statement of should be placed after the dynamic memory opening statement .
free After the str Set as NULL.
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 .Ordinary local variables are created in the stack , The function is destroyed . Global variables and are static Decorated local variables are stored in the static area , It won't be destroyed until the end of the program , So be static The life cycle of modified local variables will be longer .
typedef struct st_type
{
int i;
int a[0];// Flexible array members
}type_a;
Some compilers may report errors, which can be changed to
typedef struct st_type
{
int i;
int a[];// Flexible array members
}type_a;Flexible array members must be preceded by at least one other member .sizeof The size of the returned structure does not include the size of the flexible array members . Memory usage of structures containing flexible array members malloc Conduct dynamic development , The allocated memory should be larger than the size of the structure , To fit the expected size of the flexible array .
for example
typedef struct st_type
{
int i;
int a[0];
}type_a;
type_a *p = (type_a*)malloc(sizeof(type_a)+100*sizeof(int));
In this way, the flexible array members can be stored 100 individual int Element of type .The method of implementing flexible array can also use a pointer inside the structure , But relative to the structure, put the pointer , The flexible array only needs to be released once to release the dynamically opened memory , More advantages .
边栏推荐
- 兼容性测试知识点
- Non photorealistic rendering (NPR) paper understanding and reproduction (unity) - stylized highlights for cartoon rendering and animation
- 多坐标变换
- Advanced ROS communication mechanism
- 自动化部署项目
- Linear progression for face recognition
- 5g's past and present life -- a brief introduction to the development of mobile communication
- 哈希表简介
- 正确安装wireshark
- 多线程的知识补充
猜你喜欢

Multi threaded CAS, synchronized lock principle, JUC and deadlock

5g's past and present life -- a brief introduction to the development of mobile communication

Unity engine starts to migrate from mono to.Net coreclr

UnityShader-深度纹理(理解以及遇到的问题)

二叉树——搜索树

Interpretation of unity desktop version 7.6

ROM of IP core

数据库的索引和事务(重点)

数据库的联合查询

Understand the pointer in a picture
随机推荐
Multi threaded CAS, synchronized lock principle, JUC and deadlock
数据库在终端的增删改查
软件测试基础概念篇
ROS通信机制进阶
Related knowledge of internal classes
ROS分布式通信
Index and transaction of database (emphasis)
Programming learning records - Lesson 3 [first knowledge of C language]
5G网络身份识别---详解5G-GUTI
ROS node name duplicate
Pycharm installation and import project considerations
Remote sensing image recognition training strategy
Solving binary tree with force deduction (8)
Unityshader depth texture (understanding and problems encountered)
The problem that tqdm cannot display in a single line
UnityShader-LowPoly
导航相关消息
Related knowledge of multithreading
IP core summary
Wireshark IP address domain name resolution