当前位置:网站首页>动态内存管理
动态内存管理
2022-07-25 18:26:00 【菜菜小蒙】
常用动态内存函数介绍
目录
(1)malloc和free
void* malloc(size_t size);这个函数向内存申请一块连续可用的空间,并返回指向这块空间的指针。
该函数如果开辟成功,则会返回指向开辟好空间的指针;如果开辟失败,则返回一个NULL指针,因此malloc的返回值一定要做检查。返回类型是 void* 所以使用时根据用户需求进行类型转换。
相应的,C语言提供了另外一个函数free,专门是用来做动态内存的释放和回收的,函数原型如下:
void free (void* ptr); free函数用来释放动态开辟的内存。
如果参数 ptr 指向的空间不是动态开辟的,那free函数的行为是未定义的。如果参数 ptr 是NULL指针,则不会进行任何操作。
例:
#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;
}运行结果: ![]()
这里使用malloc函数先申请了40个字节的空间,再将空间转换为int *类型,使用整形指针p来接收。之后使用循环对申请的空间进行赋值以及打印。在这里*(p+i)与p[i]的效果相同。之后释放动态内存并把指针p置空。
(2)calloc
void* calloc (size_t num, size_t size);函数的功能是为 num 个大小为 size 的元素开辟一块空间,并且把空间的每个字节初始化为0。与函数 malloc 的区别只在于 calloc 会在返回地址之前把申请的空间的每个字节初始化为全0。
例:
#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;
}运行结果:
![]()
首先使用calloc函数申请十个整形大小的空间。利用循环对申请的空间进行输出,对比mallco函数,我们可以得出calloc函数会对申请的空间进行初始化为0。之后对申请的空间进行赋值以及打印,释放动态内存并把指针p置空。
(3)realloc
void* realloc (void* ptr, size_t size);realloc函数的出现让动态内存管理更加灵活。该函数可以对动态内存空间进行调整。
ptr 是要调整的内存地址,size 调整之后新大小,返回值为调整之后的内存起始位置。
这个函数调整原内存空间大小的基础上,还会将原来内存中的数据移动到新的空间。如果空间足够大,那么realloc函数会直接在原有的空间后追加空间;如果空间不够大,那么在堆空间上另找一个合适大小的连续空间来使用。这样函数返回的是一个新的内存地址。因此使用realloc函数需要今生判断。
#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("申请失败\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;
}运行结果:

本代码首先使用malloc函数申请40字节的内存空间,若指针p不为空,再进行赋值并打印。之后使用realloc函数进行扩容,调整后大小为80字节。因为realloc函数存在两种情况,如原有内存不够且找不到新的足够大的内存空间,realloc函数则会返回NULL。为了避免分配失败,原有空间丢失,故使用一个新的整形指针变量进行接收,若其为空则结束程序;若不为空,则将指针ptr赋值给指针p,并对新的内存空间进行赋值并打印。最后释放内存空间并将指针p置空。
边栏推荐
- Insufficient space on Disk C mklink solves vscode expansion migration to other disks
- MySQL optimistic lock
- 国际权威认可!OceanBase入选Forrester Translytical数据平台报告
- 【翻译】LFX 2022年春季导师资格开放--2月13日前申请CNCF项目!
- Partial correlation calculation of R language and partial correlations calculation using pcor function of GGM package
- Related operations of binary tree
- pd.melt() vs reshape2::melt()
- Is it true that CITIC Securities' low commission account opening is free of 5? Is it safe
- If you want to do a good job in software testing, you can first understand ast, SCA and penetration testing
- Tang's little helper
猜你喜欢

Practice of RTC performance automation tool in memory optimization scenario

CircleIndicator组件,使指示器风格更加多样化

One week activity express | in simple terms, issue 8; Meetup Chengdu station registration in progress

【网页性能优化】SPA(单页面应用)首屏加载速度慢怎么办?

Thales launches solutions to help SAP customers control cloud data

Safe operation instructions for oscilloscope probe that must be read by engineers

电流探头在ECU、电气系统电流测量的应用

Today's sleep quality record is 84 points

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

一周活动速递|深入浅出第8期;Meetup成都站报名进行中
随机推荐
MySQL index optimization introduction
Repair process of bad blocks of primary standby database
GAN的详细介绍及其应用(全面且完整)
STM32F105RBT6 内部flash调试
SQL optimizer parsing | youth training camp notes
Circulaindicator component, which makes the indicator style more diversified
JZ71 跳台阶扩展问题
C盘空间不够 mklink解决VScode扩展迁移到其他盘
Is it true that CITIC Securities' low commission account opening is free of 5? Is it safe
柔性电流探头选型指南
[QNX hypervisor 2.2 user manual]9.5 dump
How to add EXE file to boot
Express of nodejs simple example program
软件测试——常用的测试工具
BL602 开发环境搭建
Tang's little helper
Boomi won the "best CEO in diversity" and the "best company in career growth" and ranked among the top 50 in the large company category
NC68 跳台阶
uniapp滚动条置顶效果、自定义页面滚动条的位置(整理)
TESTNG中的并发测试invocationCount, threadPoolSize, timeOut的使用