当前位置:网站首页>Advanced part 5 of C language. Dynamic memory management
Advanced part 5 of C language. Dynamic memory management
2022-07-24 07:33:00 【And move forward with the high wind - & gt;】
Catalog
Why is there dynamic memory allocation
Dynamic memory allocation function
Why is there dynamic memory allocation
When creating variables, you need to allocate memory space for variables , for example :
int a=10;
char arr[20]={0};The above methods are respectively on the stack area as a Variables open up 4 Bytes of space and opened up on the stack 20 Bytes of contiguous space , The size of the above development space depends on the type of variable , The size of the array when opening up space also depends on the number of elements and the type of elements , In some application scenarios, space cannot be allocated flexibly , And the life cycle of local variables is limited , When out of scope, it is destroyed .
In order to allocate memory more reasonably , Dynamic memory allocation is introduced , As its name , You can dynamically open up memory space on demand .
Four regions :
Dynamic memory allocation function
C Language provides some dynamic memory allocation functions that can open up memory space in the heap .
void* malloc (size_t size);//size_t It's a unsigned int type
This function can open up size Bytes of space , And return a pointer to the starting address of memory , The newly opened memory space is uninitialized , It stores uncertain values .
If size by 0, The return value of a function depends on how the function is implemented , At this time, the return value cannot be dereferenced ( Usually a null pointer ).
This function may also fail to apply for space , At this time, the null pointer is returned , Therefore, functions are usually used malloc After applying for a piece of memory space, you should judge whether the return value is empty .
When the heap space is used up, it needs to be released , Otherwise, there will be a memory leak when the program is running ( When the program ends normally, the space will be automatically released by the operating system )
At this time, it should be used with another function :
void free (void* ptr);
Its function is to free the space of dynamic memory allocation , If the space pointed to is not dynamically developed , The behavior is undefined .
If ptr Null pointer , This function does nothing .
Be careful : This function does not change ptr The pointer , therefore , The pointer also points to the original space ( It needs to be left empty manually , otherwise ptr It's a wild pointer )
The other two functions that open up dynamic memory :
void* calloc (size_t num, size_t size);
calloc Functions will be opened dynamically num The space of an array of elements , The space size of each element is size byte , And each element is initialized to 0, Therefore, a total of num*size Bytes of space .
If size by 0, This function does not necessarily return a null pointer ( Depends on the implementation of the Library ), Therefore, the return value cannot be dereferenced .
void* realloc (void* ptr, size_t size);
change ptr The size of the dynamic development memory pointed to , The size of the newly opened space is the size of the past and size The lesser of , If size Bigger , The content of the newly opened memory space is uncertain .
If ptr Is a null pointer , This function has the same function as malloc The same as .
(C90 By standard ,size by 0 Is a function, the same as free, Will return a null pointer ,C99 The null pointer is not necessarily returned under the standard )
If the space development fails, a null pointer will be returned , The original ptr The memory space pointed to will not be released ( The original space is effective , Will not be changed ).
Common dynamic memory errors
1. Dereference null pointer
void test()
{
int *p = (int *)malloc(INT_MAX/4);
*p = 20;// If p The value of is NULL, There will be problems
free(p);
}2. A cross-border visit
void test()
{
int i = 0;
int *p = (int *)malloc(10*sizeof(int));
if(NULL == p)
{
exit(-1);
}
*(p+10) = 11;// A cross-border visit
free(p);
}3.free Free non dynamically opened memory
void test()
{
int a = 10;
int *p = &a;
free(p);// error
}4.free Release a part of dynamic memory
void test()
{
int *p = (int *)malloc(100);
p++;
free(p);//p No longer point to the starting position of the space opened up by dynamic memory
}5, use free Release dynamically opened memory multiple times
void test()
{
int *p = (int *)malloc(100);
free(p);
free(p);// Repeat release
}6. Forget to free dynamically opened memory
void test()
{
int *p = (int *)malloc(100);
if(NULL != p)
{
*p = 20;
}
}
int main()
{
test();// Open dynamic memory space is not released
}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 .
for example :
type_a *p = (type_a*)malloc(sizeof(type_a)+100*sizeof(int));
Is a flexible array a Opened up 4*100 Bytes of space , The memory opened up in this way is continuous
Support random access , Fast access , Less memory fragmentation .
p->i = 100;
for(int i = 0; i<100; i++) {
p->a[i] = i;
}
free(p);
边栏推荐
- Jenkins detailed deployment
- My creation anniversary
- Win10 sound icon has no sound
- django.db.utils. OperationalError: (2002, “Can‘t connect to local MySQL server through socket ‘/var/r
- Development system selection route
- numpy.cumsum
- 24. Global event bus
- MySQL statement
- OpenCascade笔记:gp包
- Customization or GM, what is the future development trend of SaaS in China?
猜你喜欢

Vulnhub DC1

Harbor2.2 quick check of user role permissions

win10声音图标有个没有声音

Single Gmv has increased 100 times. What is the "general rule" behind the rise of popular brands?

FPGA realizes reading and writing of axi4 bus

SPI - send 16 bit and 8-bit data

MITRE ATT&CK超详细学习笔记-02(大量案例)

项目中数据库插入大批量数据遇到的问题

Influxdb unauthorized access & CouchDB permission bypass

Stm32h750vbt6 drives programmable gain amplifier module pga113 -- Hal Library Based on cubemx
随机推荐
numpy.cumsum
Induction, generalization, deduction
Jackson parsing JSON detailed tutorial
开发系统选择路线
【FreeRTOS】11 软件定时器
23.组件自定义事件
[word] how to generate the index directory on the left
numpy.inf
Learning strategies of 2D target detection overview (final chapter)
django.db.utils. OperationalError: (2002, “Can‘t connect to local MySQL server through socket ‘/var/r
Who can stand it when the project goes online
Reptile learning - Overview
mysql查询当前节点的所有父级
libsvm 使用参数的基础知识笔记(1)
使用堡垒机(跳板机)登录服务器
Pytorch deep learning practice lesson 10 / assignment (basic CNN)
Deep learning two or three things - review those classical convolutional neural networks
[leetcode simple] 20. Valid brackets stack
中国三氯氢硅市场预测及战略研究报告(2022版)
Vulnhub DC1