当前位置:网站首页>[C language] the use of dynamic memory development "malloc"
[C language] the use of dynamic memory development "malloc"
2022-07-05 10:00:00 【Chenze】
write in front
Hello everyone , I'm Chen Ze , I hope after you read it , It can help you , Insufficient, please correct ! Learn and communicate together
2021 Blog star of the year, Internet of things and embedded development TOP5~2021 Blog star Top100~ Alibaba cloud expert Blogger & Star Blogger ~ Nuggets ⇿InfoQ Creator ~ Zhou Bang 71﹣ General list 1479
This paper is written by Chen Ze original CSDN If you need to reprint, please inform
Personal home page ⇲ Beating soy sauce desuCSDN Blog
Welcome to → give the thumbs-up + Collection ️ + Leaving a message.
Series column ⇥【C】 series _ Chen Ze's blog -CSDN Blog [₀~¹]
️ We are not on the stage of our choice , Acting is not the script we chose
Sunflower treasure dian
malloc() Dynamic memory development and use
calloc() Dynamic memory development and use
realloc() Dynamic memory development and use
Common errors in memory development
Static memory development ₀
Let's talk about dynamic memory development , Let's first introduce the methods we have learned to open up memory space .
char arr[10] = {0}; // Continuous development on the stack 10 Bytes of memory space
int a = 1; // Open up on the stack 4 Byte space
These are the knowledge points we learned earlier, and the common ways to open up memory space ↓
- The size of the memory space we open up is fixed .
- When we declare an array , You must specify the length in the array , In this way, the memory space it needs can be known by the compilation system . So as to get an allocation on memory .
But this leads to a problem , Sometimes, the size of space we need must be known after the program runs , The way to open up space when compiling arrays cannot be satisfied .
This is like I want to input the information of 200 students during the operation of a program , At this point, I use an array to allocate 1000 Information about a classmate . At this time, I will waste a lot of memory space . When I want to enter 2000 When I receive information from my classmates , At this time, the array is allocated 1000 Students' information cannot be stored .
Then we can use Dynamic memory development You can solve this problem perfectly .
Dynamic memory development ¹
What is dynamic memory development ?
Dynamic memory allocation (Dynamic Memory Allocation) It refers to the method of dynamically allocating or reclaiming storage space to allocate memory during program execution . Dynamic memory allocation does not need to allocate memory space in advance as static memory allocation methods such as array , But by the The system allocates according to the needs of the program , And the allocated size is the size required by the program .
Now that we have reached this point, let's talk about the concept of stack and heap n:↓ This is more convenient and easy to understand .
Stack
When executing a function , The storage units of local variables inside the function can be created on the stack , At the end of function execution, these storage units will be automatically released . The stack area mainly stores the local variables allocated by the running function , The parameters of the function , Return the data , Return address, etc .
Pile up
Variables are usually defined ( Or object ), The compiler can use this variable at compile time ( Or object ) The type of knows the size of the required memory space , Thus, the system allocates certain storage space for them at the appropriate time . This memory allocation is called Static storage allocation ; Some operands can only be determined when the program is running , So you can't reserve storage space for them at compile time , Only when the program is running , The system allocates memory according to the requirements of runtime , This method is called Dynamic storage allocation . All dynamic storage allocations are Heap area In the middle of .
When a program runs to a variable or object that needs to be dynamically allocated , You must apply to the system to get a piece of storage space of the required size in the heap , Used to store the variable or object . When the variable or object is no longer used , At the end of its life , To explicitly free the storage space it occupies , In this way, the system can reallocate the heap space , Reuse limited resources .
Next, I will introduce the use of functions for dynamic memory development , Know how to use it , Then it is equivalent to learning the dynamic memory development .
malloc() function
malloc() Declaration of functions , As shown below ↓
void* malloc (size_t size);
Allocate a memory block with a size of bytes , Returns a pointer to the beginning of the block .
The contents of the newly allocated memory block are not initialized , There are still uncertain values .
If size by 0, The return value depends on the specific library implementation ( It may be a null pointer , Maybe not ), But the returned pointer should not be dereferenced .
size→ Size of memory block , In bytes .
- Size_t Is an unsigned integer type .
success , Pointer to the memory block allocated by the function .
The type of this pointer is always void*, It can be converted to a data pointer of the desired type , So that it can be dereferenced .
If the function fails to allocate the requested memory block , Then return a null pointer NULL.
Use malloc() The function requires a header file #include<stdlib.h>
free() function
free() Declaration of functions , As shown below ↓
void free (void* ptr);
ptr → Pointer to a memory block to free memory , The memory block was previously called malloc、calloc or realloc To allocate memory . If the parameter passed is a null pointer , No action will be performed .
This function does not return any value .
actually free() Function is specially used to release or reclaim dynamic memory . Be careful :free() In the middle of ptr It points to the space of the stack area , If you store heap space, it is undefined .
When we finish recycling , It's better to ptr The parameter is set to NULL, So it can't find the original space .
Use free() The function requires a header file #include<stdlib.h>
malloc() Dynamic memory development and use
The sample code is as follows ↓
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int* p = (int*)malloc(10 * sizeof(int));
if (p == NULL)
{
perror("main:");//perror() - Print error messages
}
int i = 0;
for (i = 0; i < 10; i++)
{
*(p + i) = i;// Initialize assignment
printf("%d\n", p[i]);// Equivalent to array print elements
}
// Reclaim memory space
free(p);
p = NULL;
return 0;
}
The operation results are as follows ↓
0 1 2 3 4 5 6 7 8 9
Have you found that the access to arrays is exactly the same , Only one is in The stack area On , This is in Heap area On .
If it is malloc() The function returns a null pointer n, We just have to take malloc() Just change the memory block space . as follows ↓
int* p = (int*)malloc(1000000000000000 * sizeof(int));
The result of this operation is →Not enough space( There are not enough vacancies ) Is actually memory space .
calloc()
calloc() Declaration of functions , As shown below ↓
void* calloc (size_t num, size_t size);
by num The element array allocates a piece of memory , The size of each element is bytes long , And put all its bits Initialize to zero . The effective result is to assign a (num*size) Zero initialization memory block of bytes .
If size by 0, The return value depends on the specific library implementation ( It may be a null pointer , Maybe not ), But the returned pointer should not be dereferenced .
- Parameters
num → Number of elements to allocate .
size → The size of each element .
size_t → It's an unsigned integer .
- Return value
success , Pointer to the memory block allocated by the function .
The type of this pointer is always void*, It can be converted to a data pointer of the desired type , So that it can be dereferenced .
If the function fails to allocate the requested memory block , Then return a null pointer .
calloc() Functions and malloc() The biggest difference between functions is nothing more than :calloc() Than malloc() There is one more parameter , as well as calloc() The function of will initialize each byte to full 0, and malloc() The contents of each byte will not be initialized .calloc() Each byte of the requested space will be initialized completely before returning the address 0 Of .
calloc() Dynamic memory development and use
The sample code is as follows ↓
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int* p = (int*)calloc(10,sizeof(int));
if (p == NULL)
{
perror("main:");//perror() - Print error messages
}
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d\n", p[i]);// Equivalent to array print elements
}
// Reclaim memory space
free(p);
p = NULL;
return 0;
}
The operation results are as follows ↓
0 0 0 0 0 0 0 0 0 0
From here we can find ,calloc() The function helps us initialize to 0 Of . So if we change the code here to malloc() See what happens in the form of function , Other constant operation results of laikangkang .
int* p = (int*)malloc(10 * sizeof(int));
-842150451 → ⑩ That's ok
From here we can know malloc() Function does not help us initialize .
realloc()
realloc() Declaration of functions , As shown below ↓
void* realloc (void* ptr, size_t size);
function → Change by ptr The size of the memory block pointed to .
- Parameters
ptr → Is to adjust the memory address .
size → New size of memory block , In bytes . New size after adjustment .
size_t → It's an unsigned integer .
Return value → A pointer to the reallocated memory block , It can work with ptr identical , It can also be a new location .
The type of this pointer is void*, It can be converted to the required data pointer type , So that it can be dereferenced .
Be careful → If ptr It's a null pointer , The behavior of this function is similar to malloc(), Allocate a new block with a size of bytes , And return a pointer to the beginning of it . As shown in the following code ↓
int* p = (int*)malloc(10 * sizeof(int));
int* p = (int*)realloc(NULL,10 * sizeof(int));
In fact, it is equivalent to .
realloc() Dynamic memory development and use
The sample code is as follows ↓
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int* p = (int*)malloc(10 * sizeof(int));
if (p == NULL)
{
perror("main:");//perror() - Print error messages
}
int i = 0;
for (i = 0; i < 10; i++)
{
*(p + i) = i;
}
// Need here p The pointing space of is larger , increase 20 An integer type .realloc() - Adjust the space
int* ptr = (int*)realloc(p, 20 * sizeof(int));
if (ptr != NULL)
{
p = ptr;
}
// Reclaim memory space
free(p);
p = NULL;
return 0;
}
Check whether realloc() Adjust the p Of memory space .
Common errors in memory development
Ⅰ→ Yes NULL Dereference operation of pointer .
Ⅱ → Cross border access to dynamic open space .
Ⅲ → Use free() Free up non dynamic space .
Ⅳ → Use free() Free part of dynamic memory .
Ⅴ → For the same dynamic space , use free() Release many times .
Ⅵ → Forgetting to release the dynamically opened space will lead to memory leakage , It's more serious .
边栏推荐
- Evolution of Baidu intelligent applet patrol scheduling scheme
- 单片机原理与接口技术(ESP8266/ESP32)机器人类草稿
- uni-app---uni. Navigateto jump parameter use
- Single chip microcomputer principle and Interface Technology (esp8266/esp32) machine human draft
- Apache DolphinScheduler 入门(一篇就够了)
- Uncover the practice of Baidu intelligent testing in the field of automatic test execution
- 盗版DALL·E成梗图之王?日产5万张图像,挤爆抱抱脸服务器,OpenAI勒令改名
- 百度APP 基于Pipeline as Code的持续集成实践
- 分布式数据库下子查询和 Join 等复杂 SQL 如何实现?
- 基于模板配置的数据可视化平台
猜你喜欢
Getting started with Apache dolphin scheduler (one article is enough)
ArcGIS Pro 创建要素
单片机原理与接口技术(ESP8266/ESP32)机器人类草稿
百度智能小程序巡检调度方案演进之路
90%的人都不懂的泛型,泛型的缺陷和应用场景
[sourcetree configure SSH and use]
How to correctly evaluate video image quality
Comment obtenir le temps STW du GC (collecteur d'ordures)?
解决Navicat激活、注册时候出现No All Pattern Found的问题
[NTIRE 2022]Residual Local Feature Network for Efficient Super-Resolution
随机推荐
Charm of code language
让AI替企业做复杂决策真的靠谱吗?参与直播,斯坦福博士来分享他的选择|量子位·视点...
Officially launched! Tdengine plug-in enters the official website of grafana
百度评论中台的设计与探索
The most comprehensive promotion strategy: online and offline promotion methods of E-commerce mall
MySQL字符类型学习笔记
正式上架!TDengine 插件入驻 Grafana 官网
How to improve the operation efficiency of intra city distribution
(1) Complete the new construction of station in Niagara vykon N4 supervisor 4.8 software
QT timer realizes dynamic display of pictures
The writing speed is increased by dozens of times, and the application of tdengine in tostar intelligent factory solution
Kotlin Compose 与原生 嵌套使用
cent7安装Oracle数据库报错
【数组的中的某个属性的监听】
Six simple cases of QT
美图炒币半年亏了3个亿,华为被曝在俄罗斯扩招,AlphaGo的同类又刷爆一种棋,今日更多大新闻在此...
移动端异构运算技术-GPU OpenCL编程(进阶篇)
百度智能小程序巡檢調度方案演進之路
解决idea调试过程中liquibase – Waiting for changelog lock….导致数据库死锁问题
[200 opencv routines] 219 Add digital watermark (blind watermark)