当前位置:网站首页>[C language] dynamic memory management
[C language] dynamic memory management
2022-07-24 12:45:00 【Ahao_ te】
List of articles
1、 Dynamic memory management
1.1、 Why dynamic memory
Before we do that , Have mastered some ways to open up memory .
such as
int n = 4; // Opens the 4 Byte space
int arr[20] = {
0}; // Opened up a continuous space
The above methods have these fixed characteristics :
- Space is fixed .
- When opening up an array, you must specify the length .
But sometimes the size of space we open up can only be determined after the program runs , So there is dynamic memory .
1.2、malloc and free
C Language provides a memory development function
void* malloc (size_t size);
The opened space is stored in the stack area ,size It represents the number of bytes of space to be opened .
- If the development is successful , Will return the starting address of this space
- If the development fails , Will return null pointer
- The return value is void*, Therefore, users need to decide after development
- If size by 0, This behavior is undefined , Depends on the compiler .
free The function is used to free the memory opened up by the heap , If it is used to free the memory in the stack , Will be an error .
void free (void* ptr);
- ptr Represents the starting address of the space
- ptr by NULL When ,free Functions do nothing .
- If you don't open up dynamic memory free operation , May cause memory leaks .
malloc and free Use
int main()
{
// The size of the application space cannot be changed
int a = 10;
int arr[10];
// Need dynamic memory
int* p = (int*)malloc(40);
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
int i = 0;
for (i = 0; i < 10; i++)
{
*(p + i) = i;
}
for (i = 0; i < 10; i++)
{
printf("%d ", *(p + i));
}
// No, free
// It's not that memory space is not recycled
// When the program exits , The system will automatically reclaim memory space
free(p);
p = NULL;
return 0;
}
1.3、calloc and realloc
calloc It is also a memory function , and malloc The difference is that the data in the transmission parameter and the opened space will be initialized to 0.
void* calloc (size_t num, size_t size);
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p = (int*)calloc(10, sizeof(int)); // open up 40 Byte space
if(NULL != p)
{
//...
}
free(p);
p = NULL;
return 0;
}
realloc Function makes memory development more flexible ,realloc It can adjust the original dynamic memory space , If you increase , Then the original memory block will be preserved , The new memory block will be added later , If it gets smaller , Then the later part of the original space will be truncated .
void* realloc (void*ptr, size_t size);
- Parameters ptr The starting pointer representing the space to be expanded ,size Represents how much space needs to be expanded at last .
- ptr If NULL, Just like malloc Same function .
- void* Represents the pointer that returns the starting space after opening , This pointer should not be the same as the space start pointer that needs to be expanded at the beginning , Otherwise, when memory expansion fails , The original pointer changes to NULL.
- realloc There are two cases of adjusting the pointer , The first is when there is enough space to expand after the original space , This situation can make them spatially continuous , The address of the starting pointer remains unchanged . The second is when there is no continuous space to expand after the original space , Then we will find enough space in other places to open up space , The pointer of the original space changes .( Eventually, it becomes a space )
1.4、 Using dynamic memory allocation
This is an example of developing dynamic memory .
int* p = (int*)malloc(sizeof(int)* 10);
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
int i = 0;
for (i = 0; i < 10; i++)
{
*(p + i) = i;
}
for (i = 0; i < 10; i++)
{
printf("%d ", p[i]);
}
free(p);
p=NULL;
Symbol NULL Defined in stdio.h, The literal constant is 0. It plays a great role in the success of opening up dynamic memory space , After opening up memory , Be sure to judge whether the return pointer is null . If it's not empty , Then you will succeed in getting one p The pointer points to 10 individual int Type of space .
sizeof(int)* 10 The good thing about this is that it's cross platform , And get the right results .
If you want to access the successfully developed memory , Get in p The pointer can be separated by * (p+i)、p[ i ] Access to .
stay free ( p ) after , It is best to p To be empty (p=NULL), Prevent illegal access .
1.5、 Common dynamic memory errors
1. Do not check from malloc Whether the pointer returned by the function is NULL, Yes NULL Pointer to understand the reference
void test()
{
int* p = (int*)malloc(INT_MAX); // The memory pool does not have such a large space to allocate , Null pointer returned after development failure .
*p = 20;// It needs to be right here p Inspection , If memory allocation fails That's right NULL Pointer dereference
free(p);
}
2. Access areas outside dynamically allocated memory
int main()
{
int* p = (int*)malloc(40);
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
int i = 0;
for (i = 0; i <= 10; i++)
{
p[i] = i; // A cross-border visit
}
free(p);
p = NULL;
return 0;
}
3. towards free The function passes a value that is not generated by malloc The pointer returned by the function
void test()
{
int a = 10;
int* p = &a;
free(p);
//free Non dynamic memory will report an error
//freeNULL The pointer will not move
}
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. Access dynamic memory after it is freed
void Test(void)
{
char* str = (char*)malloc(100);
strcpy(str, "hello");
free(str); // First, the space is released
// Release should control the air
*str = 'h';
}
int main()
{
Test();
return 0;
}
6. Dynamic memory forget to release ( Memory leak )
void test()
{
int* p = (int*)malloc(100);
//....
int flag = 0;
scanf("%d", &flag);//5
if (flag == 5)
return;
free(p);
p = NULL;
}
int main()
{
test();
//......
return 0;
}
Memory leak :
When the dynamically allocated memory is no longer needed , It should be released , So it can be reassigned later . Allocating memory but not releasing it after use will cause Memory leak . In operating systems where all programs share a common memory pool , Memory leaks will drain available memory little by little , And end up with nothing . Come out of this dilemma , Just reboot the system .
1.6、 Flexible array
The last element in the structure is allowed to be an array of unknown size , This is called Flexible array members
struct S
{
int n;
int arr[0]; // Flexible array members
};
Some compilers will report errors and cannot compile. They can be changed to :
struct S
{
int n;
int arr[]; // Flexible array members
};
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 ,arr When memory is not opened up, it is called Mark
- 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 .
struct S
{
int n;
int arr[]; // Flexible array members
};
printf("%d\n",sizeof(struct S)); //4
The use of flexible arrays :
struct S
{
int n;
int arr[]; // no need int* p Why
};
// If you use int* p; You need to give structure members p Open up another memory space for p Point to .
// no need int* p Why
//1. use int*p Need to open up two different spaces ,free You have to release it twice , belt arr[] as long as free Easy release at one time
//2. Open up two different spaces , Memory fragmentation will occur , Continuous memory is beneficial to the improvement of access speed
int main()
{
struct S* ps = (struct S*)malloc(sizeof(struct S) + 40);
if (ps == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
ps->n = 100;
int i = 0;
for (i = 0; i < 10; i++)
{
ps->arr[i] = i;
}
for (i = 0; i < 10; i++)
{
printf("%d ", ps->arr[i]);
}
struct S* ptr = (struct S*)realloc(ps, sizeof(struct S) + 80);
if (ptr != NULL)
{
ps = ptr;
ptr = NULL;
}
free(ps);
ps = NULL;
return 0;
}
边栏推荐
- Okaleido tiger NFT即将登录Binance NFT平台
- Industry insight | how to better build a data center? It and business should "go together"
- 让一套代码完美适配各种屏幕
- Ape anthropology topic 5
- 中国消费者和产业链都很难离开苹果,iPhone的影响力太大了
- Prototype inheritance
- Static attribute, super()
- 猿人学第五题
- ThinkPHP realizes database backup
- Is it safe to contact the account manager online to open a fund account?
猜你喜欢
让一套代码完美适配各种屏幕

深圳地铁12号线第二批工程验收通过 预计7月28日试运行
![[function test] test of the project - login and post function](/img/64/c9bbf34964622f4f013b1184eeb1e0.jpg)
[function test] test of the project - login and post function

【C语言】详细的文件操作相关知识

Summary of recent interviews

国产旗舰手机定价近六千,却连iPhone12都打不过,用户选谁很明确

Behind the rapid growth, Huawei cloud Wulanchabu data center is the green way

Implementing deep learning framework from zero -- further exploration of the implementation of multilayer bidirectional RNN

MobileViT:挑战MobileNet端侧霸主
![[rust] reference and borrowing, string slice type (& STR) - rust language foundation 12](/img/48/7a1777b735312f29d3a4016a14598c.png)
[rust] reference and borrowing, string slice type (& STR) - rust language foundation 12
随机推荐
Okaleido tiger NFT即将登录Binance NFT平台
6-16 vulnerability exploitation -rlogin maximum permission login
Static attribute, super()
生信识图 之 点图基础
TypeNameExtractor could not be found
Unity rotation test
Okaleido tiger NFT is about to log in to binance NFT platform
English grammar_ Indefinite pronouns - Overview
手把手教你用 Power BI 实现 4 种可视化图表
The second batch of projects of Shenzhen Metro Line 12 passed the acceptance and is expected to be put into trial operation on July 28
如何在IM系统中实现抢红包功能?
有没有2、3w前期适合一个人干的创业项目呢?做自媒体可以吗?
Wechat applet - drawing dashboard
regular
如何使用autofs挂载NFS共享
Everything about native crash
ASP. Net core deployment Manual: 1. Deployment Basics
The seventh topic of ape Anthropology
雪花算法(PHP)
以Chef和Ansible为例快速入门服务器配置