当前位置:网站首页>[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
- vsftp 与 TFTP 与 samba 与 nfs 复习
- FPGA Development (2) -- IIC communication
- Some specifications based on zfoo development project
- Solr基础操作10
- Will the flush SQL CDC parallelism affect the order? Generally, only 1 can be set for data synchronization.
- Cloud native enthusiast weekly: cool collection of grafana monitoring panels
- FPGA Development (1) -- serial port communication
- Root cause of glideexception: failed decodepath{directbytebuffer- > gifdrawable- > drawable}
- Official website of Greentree
猜你喜欢

Vulnhub靶机-MoriartyCorp
![克隆無向圖[bfs訪問每條邊而不止節點]](/img/34/2a1b737b6095293f868ec6aec0ceeb.png)
克隆無向圖[bfs訪問每條邊而不止節點]

Inspiration collection · evaluation of creative writing software: flomo, obsidian memo, napkin, flowus

Simple understanding of B tree and b+ tree

Leetcode (680) -- verifying palindrome string II

QT learning 01 GUI program principle analysis

Serialization of binary tree 297 Serialization and deserialization of binary tree 652 Find duplicate subtrees

What is IGMP? What is the difference between IGMP and ICMP?

6.28 problem solving

The role of VMware virtual machine
随机推荐
Basic tutorial for installing monggodb in win10
蛇形矩阵(数组模拟方向, d代表转弯)
EB-5 immigration in the United States reappears to be positive, and the reauthorization policy of the regional center is suspended
js中的事件
Sword finger offer 14- I. cut rope
Halcon practical: design idea of solder joint detection
Unity about failure (delay) of destroy and ondestroy
Viewing splitchunks code segmentation from MPX resource construction optimization
Solr基础操作11
Solr基础操作14
[advanced C language] string and memory function (I)
爬虫入门实战:斗鱼弹幕数据抓取,附送11节入门笔记
After crossing, she said that the multiverse really exists
Getting started with qpainter: drawing the chess interface
QPainter的使用入门:绘制象棋界面
Bee common configuration
Three postures of anti CSRF blasting
Exploration and Practice on the future direction of byte cloud database
克隆無向圖[bfs訪問每條邊而不止節點]
The role of VMware virtual machine