当前位置:网站首页>[advanced C language] dynamic memory management
[advanced C language] dynamic memory management
2022-06-30 00:10:00 【Haozai lives today】
List of articles
1、 Why is there dynamic memory allocation
1、 There are three areas in memory : The stack area 、 Heap area 、 Static zone
2、 The stack area Store temporary variables in , Static zone Static variables and static variables , Heap area Is used for dynamic memory allocation
3、 Dynamic memory allocation requires malloc,calloc,realloc,free function
2、malloc Functions and free function
1、malloc Function header file “stdlib.h”
2、malloc Function USES
#include<errno.h>
#include<string.h>
#include<stdlib.h>
int main()
{
// open up 10 An integer space
int* p = (int*)malloc(40);
//malloc Open space is opened by one byte
// So open up 10 An integer , want 40 Bytes
if (NULL == p)// If null pointer is returned , Space development failed
{
printf("%s\n", strerror(errno));// Error reporting function
return 0;
}
// Use
int i = 0;
for (i = 0; i < 10; i++)
{
*(p + i) = i;
}
for (i = 0; i < 10; i++)
{
printf("%d ", p[i]);
}
// Release
free(p);// When released p It becomes a wild pointer
p = NULL;// Therefore, we usually process the pointer into a null pointer after release
return 0;
}
3、calloc function
1、 Open up and 0 Initialize the open space
2、calloc Use of functions
#include<errno.h>
#include<string.h>
#include<stdlib.h>
int main()
{
// open up 10 An integer space
int* p = (int*)calloc(10,sizeof(int));
//calloc The required parameters are the number of elements and the size of the application elements
if (NULL == p)// If null pointer is returned , Space development failed
{
printf("%s\n", strerror(errno));// Error reporting function
return 0;
}
// Use
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", p[i]);
}
// Release
free(p);// When released p It becomes a wild pointer
p = NULL;// Therefore, we usually process the pointer into a null pointer after release
return 0;
}
4、realloc function
1、 Functions that reopen space
2、realloc Function use case
#include<errno.h>
#include<string.h>
#include<stdlib.h>
int main()
{
// open up 10 An integer space
int* p = (int*)calloc(10, sizeof(int));
//calloc The required parameters are the number of elements and the size of each element
if (NULL == p)// If null pointer is returned , Space development failed
{
printf("%s\n", strerror(errno));// Error reporting function
return 0;
}
// Use
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", p[i]);
}
// Need to expand
int* ptr = (int*)realloc(p,80);
if (NULL != ptr)
{
p = ptr;
ptr = NULL;
}
// Release
free(p);// When released p It becomes a wild pointer
p = NULL;// Therefore, we usually process the pointer into a null pointer after release
return 0;
}
3、 if realloc The function is written in the following form , Its functions and functions malloc The function is the same
int* p = (int*)realloc(NULL,40);
5、 Common errors when using dynamic memory space
1、 Yes NULL Pointer dereference
Examples of mistakes are as follows
#include <limits.h>
#include <stdlib.h>
int main()
{
int* p = (int*)malloc(INT_MAX);// The application space is too large , Unable to apply , return NULL
if (p == NULL)// Without this judgment
return 0;// Will cause access to NULL Pointer error
int i = 0;
for (i = 0; i < 10; i++)
{
*(p + i) = i;
}
return 0;
}
2、 Out of bounds access to dynamic memory space
Examples of mistakes are as follows
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main()
{
char* p = (char*)malloc(10 * sizeof(char));
if (p == NULL)
{
printf("%s\n", strerror(errno));
}
// Use
int i = 0;
for (i = 0; i <= 10; i++)// here <=10 A total of 11 Elements
// and malloc Only applied for 10 Space , Form cross-border visits
{
*(p + i) = 'a' + i;
}
// Release
free(p);
p = NULL;
return 0;
}
3、 Use of non dynamic memory free Release
Examples of mistakes are as follows
int main()
{
int a = 10;// Memory requested on stack , It will be automatically destroyed after it is out of the scope
int* p = &a;// Unwanted free, So this code is wrong
free(p);
p = NULL;
return 0;
}
4、 Use free Release a piece of dynamic memory
Examples of mistakes are as follows
int main()
{
int* p = (int*)malloc(40);
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
// Using memory
int i = 0;
//1~5
for (i = 0; i < 5; i++)
{
*p = i + 1;
p++;// Here and now p The pointer has moved , Not in its original position
}
// Release
free(p);// Releasing dynamic memory can't release only a part , So the mistake
p = NULL;
return 0;
}
5、 Dynamic memory forget to release
Examples of mistakes are as follows
void test()
{
int* p = (int*)malloc(100);
if (p == NULL)
{
return 0;
}
// Forget to release after use , There will be a memory leak , So the mistake
}
int main()
{
test();
return 0;
}
6、 Flexible array
Flexible array features :
1、 A flexible array member in a structure must have at least one other member in front of it
2、sizeof The returned structure size does not contain the memory of the flexible array
3、 Structures that contain flexible array members use malloc() Function for dynamic memory allocation , 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 , The size is unspecified
}
int main()
{
//printf("%d\n",sizeof(struct S));
// When calculating the size of the structure , The size of the flexible array is ignored
struct S* ps = (struct S*)malloc(sizeof(struct S) + 40);
ps->n = 100;
int i = 0;
for(i = 0; i < 10; i++)
{
ps->arr[i] = i;
}
// increase capacity
struct S* ptr = (struct S*)realloc(pc, sizeof(struct S) + 80);
if(ptr == NULL)
{
return 0;
}
else
{
ps = ptr;
}
// Release
free(ps);
ps = NULL;
return 0
}
Method 2 、
The defect of method 2 :
1、 Open up and release more times , It's easy to make mistakes
2、 When there are many times of development , Prone to memory fragmentation
struct S
{
int n;
int* arr;
}
int main()
{
struct S* ps = (struct S*)malloc(sizeof(struct S));
pc->n = 100;
ps->arr = (int*)malloc(40);
// Release ( Disadvantages of method 2 , Open up and release more times , It's easy to make mistakes )
free(ps->arr);
ps->arr = NULL;
free(ps);
ps = NULL;
return 0;
}
7、 Small exercise
Exercise one 、
char* GetMemory(char* p)
{
p = (char*)malloc(100);
return p;
}
void Test(void)
{
char* str = NULL;
str = GetMemory(str);
strcpy(str, "hello world");
printf(str);
// Release
free(str);
str = NULL;
}
int main()
{
Test();
return 0;
}
Exercise 2 、
char* GetMemory(char* p)
{
p = (char*)malloc(100);
return p;
}
void Test(void)
{
char* str = NULL;
GetMemory(&str);
strcpy(str, "hello world");
printf(str);
// Release
free(str);
str = NULL;
}
int main()
{
Test();
return 0;
}
Practice three 、
#include <stdio.h>
void Test(void)
{
char* str = (char*)malloc(100);
strcpy(str, "hello");
free(str);
str = NULL;
if (str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
int main()
{
Test();
return 0;
}
边栏推荐
- Solr basic operation 8
- 【微信小程序】认识小程序项目的基本组成结构
- Solr basic operation 16
- Solr基础操作16
- This simple little function saves 213 hours for our production research team in half a year
- After crossing, she said that the multiverse really exists
- 一步步教你在Edge浏览器上安装网风笔记
- Leetcode (76) -- Minimum Covering substring
- 西门子低代码 9.14版本: 满足不同需求
- This PMP Exam (June 25), some people are happy and others are worried. That's why
猜你喜欢

Teach you step by step to install webwind notes on edge browser
![Cloner un Graphe non recté [bfs accède à chaque bord et pas seulement aux noeuds]](/img/34/2a1b737b6095293f868ec6aec0ceeb.png)
Cloner un Graphe non recté [bfs accède à chaque bord et pas seulement aux noeuds]

QT learning 06 widgets and window types

Koa2 learning and using

Digital collection of cultural relics, opening a new way of cultural inheritance

JS draw polar color gradient

Basic operations such as MySQL startup under Windows platform

西门子低代码平台通过Database Connector 连接Mysql 实现增删改查

QT learning 07 coordinate system in QT
![[advanced C language] address book implementation](/img/e6/8a51d519d31ec323cf04c59a556325.png)
[advanced C language] address book implementation
随机推荐
js中的事件
Do mysqlcdc data not support windowing functions like row_ Number, lead
JS的初步语法
Summarize Flink runtime architecture in simple terms
Solr basic operations 12
Bee常用配置
这次的PMP考试(6月25日),有人欢喜有人忧,原因就在这...
Golang泛型的巧妙应用,防止变量空指针错误,防止结构体字段空指针错误
Table responsive layout tips for super nice
[advanced C language] string and memory function (I)
How to write controller layer code gracefully?
一步步教你在Edge浏览器上安装网风笔记
Unity about failure (delay) of destroy and ondestroy
Serialization of binary tree 297 Serialization and deserialization of binary tree 652 Find duplicate subtrees
多数元素II[求众数类之摩尔投票法]
How to realize the spelling correction function in search engine
漫画安全HIDS、EDR、NDR、XDR
Construction of module 5 of actual combat Battalion
JVM之栈空间
Leetcode (76) -- Minimum Covering substring