当前位置:网站首页>C language dynamic memory management
C language dynamic memory management
2022-07-26 23:23:00 【Salted fish with dreams】
1. Dynamic memory functions
1.malloc Functions and free function
malloc Function declaration of function :
void* malloc (size_t size);malloc Functions and free Function header files are
#include <stdlib.h>malloc The function requests a contiguous available space from memory , 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 , Specifically, when using, the user himself
To decide .
If parameters size by 0,malloc The standard is undefined , Depends on the compiler
free The function is dedicated to the collection and release of dynamic memory .
free The function of is declared as :
void free (void* ptr); about free function :
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 .
(free Function will also be used in the following dynamic memory functions , Its effect and use method are the same )
Take one about malloc Functions and free Examples of functions
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>//malloc and free The header file
#include <string.h>
#include <errno.h>
int main()
{
int arr[10] = { 0 };
int* p = (int*)malloc(40);// The return value is void* Set the type yourself
// If the development is successful, a pointer to the developed space will be returned
// If the development fails, it returns NULL The pointer
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Use
int i;
for (i = 0; i < 10; i++)
{
*(p + i) = i;
}
for (i = 0; i < 10; i++)
{
printf("%d\n", *(p + i));
}
// Free up memory
free(p);// Dynamic memory release and recycling
// if free What is released is not dynamic memory Situation undefined
p = NULL;
return 0;
}2.calloc function
calloc Function is also used for dynamic memory allocation , Its usage and malloc be similar , But one more parameter , And it can initialize the opened space , Its effect is equivalent to malloc Function plus memset A combination of functions .
calloc The function of is declared as :
void* calloc (size_t num, size_t size);calloc The function :
by num Size is size The elements of open up a space , And initialize each byte of the space to 0.
And functions malloc The difference is that calloc Initializes each byte of the requested space to full before returning the address 0.
for instance :
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main()
{
int* p = (int*)calloc(10, sizeof(int));//calloc The opened memory will be initialized to 0
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Print
int i;
for (i = 0; i < 10; i++)
{
printf("%d\n", *(p + i));
}
// Release
free(p);
p = NULL;
return 0;
}If the opened space is initialized as 0 The needs of The use calloc The function doesn't fit .
3.realloc function
Its function is declared as :
void* realloc (void* ptr, size_t size);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 a reasonable time
Waiting memory , We will make flexible adjustments to the size of memory . that realloc Function can be used to dynamically open up the memory size
Adjustment of .
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 , It will also move the data in the original memory to a new space
realloc There are two ways to adjust memory space :
situation 1: There is enough space behind the original space
situation 2: There is not enough space after the original space
When it's the case 1 When , To expand memory, add space directly after the original memory , The original spatial data does not change .
When it's the case 2 When , When there is not enough space after the original space , The way to expand is : Find another suitable size on the heap space
Continuous space to use . This function returns a new memory address .
Because of the above two situations ,realloc We should pay attention to the use of functions .
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main()
{
int* p = (int*)malloc(40);
if (p == NULL)
{
printf("%s\n", strerror(errno));
}
// Use
int i;
for (i = 0; i < 10; i++)
{
*(p + i) = i + 1;
}
// Capacity expansion
int* ptr = (int*)realloc(p, 80);// Expand to 80 Bytes Equivalent to the original 40 Plus 40
// Don't directly use the original pointer to receive If realloc return NULL It may lead to data loss
if (ptr != NULL)
{
p = ptr;
}
for (i = 0; i < 10; i++)
{
printf("%d ", *(p + i));
}
//realloc(NULL, 40) Equivalent to malloc(40);
return 0;
}2. Common dynamic memory errors
1. Yes NULL Dereference operation of pointer .
2. Cross border access to dynamic open space .
3. Use of non dynamic memory free Release
4. Use free Release a piece of dynamic memory
5. Multiple releases of the same dynamic memory
6. Dynamic memory forget to release ( Memory leak )
3. Flexible array
1. Definition method of flexible array
struct S
{
int i;
int a[0];// Flexible array members
};Some compilers may report errors , Then it can be changed to the following :
struct S
{
int i;
int a[];// Flexible array members
};2. Characteristics and use 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
Small , To fit the expected size of the flexible array .
Use :
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
struct S
{
int n;
int arr[];
};
int main()
{
int sz = sizeof(struct S);//4 Structure memory does not calculate flexible arrays
printf("%d\n", sz);
// Use of flexible numbers
struct S* ps = (struct S*)malloc(sizeof(struct S) + 40);
if (ps == NULL)
{
return 1;
}
int i;
for (i = 0; i < 10; i++)
{
*(ps->arr + i) = i;
}
for (i = 0; i < 10; i++)
{
printf("%d ", ps->arr[i]);
}
struct S* str = (struct S*)realloc(ps, sizeof(struct S) + 80);
if (str != NULL)
{
ps = str;
}
// Release
free(ps);
ps = NULL;
return 0;
}3. The advantages of flexible arrays
The above use can also be written in the following form :
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
struct S
{
int n;
int* arr;
};
int main()
{
// Use of flexible numbers
struct S* ps = (struct S*)malloc(sizeof(struct S));
if (ps == NULL)
{
return 1;
}
ps->n = 100;
int* p = (int*)malloc(40);
if (p != NULL)
{
ps->arr = p;
}
int i;
for (i = 0; i < 10; i++)
{
*(ps->arr + i) = i;
}
for (i = 0; i < 10; i++)
{
printf("%d ", ps->arr[i]);
}
struct S* str = (struct S*)realloc(ps, sizeof(struct S) + 80);
if (str != NULL)
{
ps = str;
}
// Release
free(ps->arr);
ps->arr = NULL;
free(ps);
ps = NULL;
return 0;
}Compared with the following The benefits of using flexible arrays are obvious
First , Convenient memory release .
If our code is in a function for others , You do a secondary memory allocation in it , And return the whole structure to the user . The user calls free You can release the structure , But the user doesn't know that the members in the structure also need free, So you can't expect users to find out . therefore , If we allocate the memory of the structure and its members at one time , And return a structure pointer to the user , The user does it once free You can also free up all the memory .
second , This is good for access speed .
Continuous memory is good for improving access speed , It also helps reduce memory fragmentation .
边栏推荐
- Disk expansion process and problems encountered in the virtual machine created by VMWare
- 企业数据治理面临的六大挑战!
- MySQL syntax uses detailed code version
- PostgreSQL 与 Navicat:数据库行业的中坚力量
- Easily implement seckill system with redis! (including code)
- The memory occupation of the computer is too high after it is turned on (more than 50%)
- Day07 MySql知识点再总结与多表查询
- 科研太忙无法顾家?陈婷:人生不能只有一个支点
- New thrust of Moore's law, detailed explanation of Intel Advanced Packaging Technology!
- 每周招聘|PostgreSQL数据库研发工程师,年薪60+,名企高薪,挑战自我!
猜你喜欢
![[postgresql]postgresqlg使用enerate_series() 函数补全统计](/img/62/893986eb97a61f4e9ef32abc8d2a90.png)
[postgresql]postgresqlg使用enerate_series() 函数补全统计
![[hcip] OSPF route calculation](/img/1c/ee9eee2e723b850c401f7cddda1b27.png)
[hcip] OSPF route calculation

The interviewer asked: this point of JS

公有云安全性和合规性方面的考虑事项

测试开发是开发吗?

华裔科学家Ashe教授对涉嫌造假的Nature论文的正面回应

Practical project: boost search engine

ESMFold: AlphaFold2之后蛋白质结构预测的新突破

Science | University of Washington uses AI and structural prediction to design new proteins
The memory occupation of the computer is too high after it is turned on (more than 50%)
随机推荐
Monte Carlo search tree (UCT) based on confidence upper bound to realize four sub chess
Do you know the common core types of magnetic ring inductors?
HCIA-R&S自用笔记(18)园区网架构基础、交换机工作原理、VLAN原理
Introduction to the use of Jerry downloader forced download tool_ Ac695n696nad14ad15 full range support
Hcia-r & s self use notes (19) VLAN configuration and experiment, routing between VLANs
Weilai cup 2022 Niuke summer multi school training camp 2
Typescript stage learning
科研太忙无法顾家?陈婷:人生不能只有一个支点
HCIA-R&S自用笔记(23)DHCP
Signal debugging document developed by car
New thrust of Moore's law, detailed explanation of Intel Advanced Packaging Technology!
SQL 基础知识
kalibr标定realsenseD435i --多相机标定
Basic use of gateway
Lesson 2 of Silicon Valley classroom - building project environment and developing lecturer management interface
How to use data pipeline to realize test modernization
SQL multi table query exercise
Disk expansion process and problems encountered in the virtual machine created by VMWare
企业如何缓解物联网和工业物联网安全风险
Science | 华盛顿大学利用AI和结构预测设计全新蛋白质