当前位置:网站首页>Introduction to dynamic memory functions (malloc free calloc realloc)
Introduction to dynamic memory functions (malloc free calloc realloc)
2022-07-27 05:04:00 【~Xiao Ming learns programming】
author :~ Xiao Ming learns programming
Article column :C Basic knowledge of language
All you can see is memories , What you want is the past
Preface
When we write code, we will encounter the following situations : For example, when we use arrays, we will open up a space
int arr[10]={
0};
In this way, we have opened up a piece 40 Bytes of space , But when we want to use 50 even to the extent that 60 What should I do with a space of bytes ? That we use a lot C95 Under the version , The open space in the array is fixed , Because we need to pass in constants, we can't flexibly open up space , So we must use dynamic memory management , Today I will introduce some functions related to dynamic memory development .
malloc

Let's first introduce this function :
This function applies to memory for a contiguous block of free space , And return the pointer to this space .
If the development is successful , Then return a pointer to open a good space .
If the development fails , Returns a NULL The pointer , therefore malloc The return value of must be checked .
The type of return value is void , therefore malloc Function doesn't know the type of open space , The user will decide when using it .
If parameters size by 0,malloc The standard is undefined , Depends on the compiler .
free
C Language provides another function free, It is specially used for dynamic memory release and recovery , The function prototype is as follows :
free Function is used to release memory opened dynamically .
If parameters ptr The pointed space is not opened dynamically , that free The behavior of a function is undefined .
If parameters ptr yes NULL The pointer , Then the function does nothing .
The following is a code demonstration
#include <stdio.h>
int main()
{
// Code 1
int num = 0;
scanf("%d", &num);
int arr[num] = {
0 };
// Code 2
int* ptr = NULL;
ptr = (int*)malloc(num * sizeof(int));
if (NULL != ptr)// Judge ptr Is the pointer null
{
int i = 0;
for (i = 0; i < num; i++)
{
*(ptr + i) = 0;
}
}
free(ptr);// Release ptr The dynamic memory pointed to
ptr = NULL;// Is it necessary to ?
return 0;
}
calloc

C The language also provides a function called calloc , calloc Function is also used for dynamic memory allocation .
- The function is for num Size is size The elements of open up a space , And initialize each byte of the space to 0.
- And functions malloc The only difference is calloc Initializes each byte of the requested space to full before returning the address 0.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p = (int*)calloc(10, sizeof(int));
if(NULL != p)
{
// Use space
}
free(p);
p = NULL;
return 0; }
So how do we request initialization for the contents of the requested memory space , So it's easy to use calloc Function to complete the task .
realloc

realloc Functions make dynamic memory management more flexible .
Sometimes we find that the application space is too small in the past , Sometimes we think the application space is too large , That's for reasonable time memory , We will make flexible adjustments to the size of memory . that realloc Function can be used to adjust the dynamic memory size .
ptr Is the memory address to be adjusted
size New size after adjustment
The return value is the starting memory position after adjustment .
This function adjusts the size of the original memory space , The original data in memory will also be moved to New space .
realloc There are two ways to adjust memory space :
situation 1: There is enough space behind the original space
situation 2: There is not enough space after the original space
situation 1
When it's the case 1 When , To expand memory, add space directly after the original memory , The original spatial data does not change .
situation 2
When it's the case 2 When , When there is not enough space after the original space , The way to expand is : Find another suitable size on the heap space
Continuous space to use . This function returns a new memory address .
Because of the above two situations ,realloc We should pay attention to the use of functions
#include <stdio.h>
int main()
{
int *ptr = (int*)malloc(100);
if(ptr != NULL)
{
// Business processing
}
else
{
exit(EXIT_FAILURE);
}
// Expand capacity
// Code 1
ptr = (int*)realloc(ptr, 1000);// Is this ok? ?( What happens if the application fails ?)
// Code 2
int*p = NULL;
p = realloc(ptr, 1000);
if(p != NULL)
{
ptr = p;
}
// Business processing
free(ptr);
return 0; }
边栏推荐
- ps太卡怎么办?几步帮您解决问题
- JS tips
- [untitled] I is circularly accumulated under certain conditions. The condition is usually the length of the loop array. When it exceeds the length, the loop will stop. Because the object cannot judge
- 写代码涉及到的斜杠/和反斜杠\
- 事件的接受与忽略
- 2019 top tennis cup upload
- Advantages of smart exhibition hall design and applicable industry analysis
- 自定义视口高度,多余的部分使用滚动
- vim的基本操作
- On the problem that Gorm's beforedelete hook method does not work
猜你喜欢

How to import PS style? Photoshop style import tutorial

What if Photoshop prompts that the temporary storage disk is full? How to solve the problem that PS temporary storage disk is full?

Solution: how to use bash batch command in win10

再一个技巧,每月稳赚3万+

Advantages of smart exhibition hall design and applicable industry analysis

Photoshop裁剪工具隐藏技巧

MySQL download and installation & perfect uninstall

OFDM 十六讲 2- OFDM and the DFT

Why is count (*) slow

二、MySQL高级
随机推荐
背包问题dp
Comprehensive experiment of static routing
多态的详讲
Affine transformation module and conditional batch Standardization (CBN) of detailed text generated images
「Photoshop2021入门教程」调整图片到不同的长宽比
Three paradigms, constraints, some keyword differences,
[untitled] I is circularly accumulated under certain conditions. The condition is usually the length of the loop array. When it exceeds the length, the loop will stop. Because the object cannot judge
【搜索】—— 多源BFS + 最小步数模型
TCP three handshakes and four disconnects
Advantages of smart exhibition hall design and applicable industry analysis
Easily download data in power Bi reports with power auto
.htaccess learning
Unit test Chapter6
[C language] detailed explanation of user-defined types (structure + enumeration + Union)
R-score reproduction R-Precision evaluation index quantitative text generation image r-score quantitative experiment whole process reproduction (R-Precision) quantitative evaluation experiment step on
【报错】:Cannot read properties of undefined (reading ‘prototype‘)
Standard dialog qmessagebox
Install pyGame
2022 T2i text generated image Chinese Journal Paper quick view-1 (ecagan: text generated image method based on channel attention mechanism +cae-gan: text generated image technology based on transforme
vim的基本操作
