当前位置:网站首页>Dynamic memory management
Dynamic memory management
2022-07-25 18:34:00 【Caicaixiaomeng】
Introduction to common dynamic memory functions
Catalog
Introduction to common dynamic memory functions
(1)malloc and free
void* malloc(size_t size);This function applies to memory for a contiguous block of free space , And return the pointer to this space .
If this function is successfully developed , Will return the pointer to the opened space ; If the development fails , Returns a NULL The pointer , therefore malloc The return value of must be checked . The return type is void* Therefore, type conversion is carried out according to user requirements .
Corresponding ,C Language provides another function free, It is specially used for dynamic memory release and recovery , The function prototype is as follows :
void free (void* ptr); 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 , No action will be taken .
example :
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* p = (int*)malloc(40);
if (p != NULL)
{
for (int i = 0; i < 10; i++)
{
*(p + i) = i;
}
for (int j = 0; j < 10; j++)
{
printf("%d ", p[j]);
}
}
free(p);
p = NULL;
return 0;
} Running results : ![]()
Use here malloc Function applied first 40 Bytes of space , Then convert the space into int * type , Use an integer pointer p To receive . Then use the cycle to assign and print the applied space . ad locum *(p+i) And p[i] The effect is the same . Then release the dynamic memory and put the pointer p empty .
(2)calloc
void* calloc (size_t num, size_t size);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.
example :
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* p = (int*)calloc(10, sizeof(int));
if (p != NULL)
{
for (int i = 0; i < 10; i++)
{
printf("%d ", p[i]);
}
printf("\n");
for (int j = 0; j < 10; j++)
{
*(p + j) = j;
}
for (int k = 0; k < 10; k++)
{
printf("%d ", p[k]);
}
}
free(p);
p = NULL;
return 0;
}Running results :
![]()
use first calloc The function applies for ten spaces of integer size . Use the cycle to output the applied space , contrast mallco function , We can figure out calloc The function initializes the requested space to 0. Then assign and print the applied space , Free dynamic memory and put the pointer p empty .
(3)realloc
void* realloc (void* ptr, size_t size);realloc Functions make dynamic memory management more flexible . This function can adjust the dynamic memory space .
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 , It will also move the data in the original memory to a new space . If the space is large enough , that realloc Function will directly add space after the original space ; If the space is not big enough , Then find another continuous space of appropriate size on the heap space to use . This function returns a new memory address . Therefore use realloc Functions need to be judged in this life .
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* p = (int*)malloc(40);
if (p != NULL)
{
for (int i = 0; i < 10; i++)
{
p[i] = i;
}
for (int j = 0; j < 10; j++)
{
printf("%d ", p[j]);
}
printf("\n");
}
int* ptr = (int*)realloc(p, 80);
if (ptr == NULL)
{
printf(" Application failed \n");
return 1;
}
else
{
p = ptr;
for (int i = 0; i < 20; i++)
{
p[i] = i;
}
for (int j = 0; j < 20; j++)
{
printf("%d ", p[j]);
}
printf("\n");
}
free(p);
p = NULL;
return 0;
}Running results :

This code first uses malloc Function request 40 Byte memory space , If pointer p Not empty , Then assign values and print . Then use realloc Function , Resized to 80 byte . because realloc There are two cases of functions , For example, the original memory is insufficient and a new memory space of sufficient size cannot be found ,realloc The function returns NULL. To avoid allocation failure , The original space is lost , Therefore, a new integer pointer variable is used to receive , If it is empty, end the program ; If not be empty , The pointer ptr Assign a value to a pointer p, And assign a value to the new memory space and print . Finally, free the memory space and put the pointer p empty .
边栏推荐
- SQL things
- Tensor to img & imge to tensor (tensor conversion of pytorch)
- 11.2-hj86 find the maximum number of continuous bits
- Trust multithread security count
- Is it true that CITIC Securities' low commission account opening is free of 5? Is it safe
- Conversion between integer and string in C language
- Diagonalization, power of a
- 什么是3DE体验平台
- 网易严选库存中心设计实践
- MySQL index optimization introduction
猜你喜欢

1---电子实物认知

Save the image with gaussdb (for redis), and the recommended business can easily reduce the cost by 60%

Related operations of figure

如何创建一个有效的帮助文档?

Combined with GHS multi, use Reza E1 simulator to realize the simulation and debugging of Reza rh850 single chip microcomputer

Stm8s003f3 internal flash debugging

大厂云业务调整,新一轮战争转向

Detailed introduction and application of GaN (comprehensive and complete)

【华为机试真题】字符串匹配

Design practice of Netease strictly selecting inventory center
随机推荐
Number two 2010 real test site
Disk performance and capacity
MySQL index optimization introduction
请问什么是国债逆回购?安全吗?
Related operations of figure
基于Caffe ResNet-50网络实现图片分类(仅推理)的实验复现
结合GHS MULTI使用瑞萨E1仿真器实现对瑞萨RH850单片机的仿真调试
ESP32 S3 vscode+idf搭建
Safe operation instructions for oscilloscope probe that must be read by engineers
Care for front-line epidemic prevention workers, Haocheng JIAYE and Gaomidian sub district office jointly build the great wall of public welfare
Experimental reproduction of image classification (reasoning only) based on caffe resnet-50 network
Tkinter GUI address book management system
Ceres curve fitting
【网页性能优化】SPA(单页面应用)首屏加载速度慢怎么办?
How to add EXE file to boot
什么是3DE体验平台
Oracle import error: imp-00038: unable to convert to environment character set handle
通讯录(二)
uniapp滚动条置顶效果、自定义页面滚动条的位置(整理)
Pan domain name configuration method