当前位置:网站首页>C language dynamic memory management
C language dynamic memory management
2022-07-19 05:30:00 【Learn to put down ta】
C Four functions of language memory management
1、malloc function
grammar :malloc( You need to apply for the size of memory space ), Default return void* Type pointer , But for convenience , When returning, convert the type
char * ptr;
ptr = (char *)malloc(sizeof(char)*4);
because malloc Function will not help you initialize the requested space , So you need to initialize yourself , You can also use (string.h) Library function memset(void*,void,sizeof()) For initialization, you can also use
2、calloc function
Syntax and malloc Exactly the same as , The only difference is calloc Will be initialized automatically , The number is initialized to 0, Characters are initialized to spaces by default
char * ptr;
ptr = (char *)calloc(sizeof(char)*4);
When the space of your first application is insufficient, you need to apply for a second time and copy the data of the first time string.h) Library function memcpy(void*,void*,int) Of course, you can also use
3、realloc function
This function can be understood as adding x Data , You need it. realloc(ptr, Original number +x), The original data remains unchanged
char * ptr;
ptr = (char *)malloc(sizeof(char)*2);
// Yes ptr Carry out a series of operations
ptr = (char *)realloc(ptr,sizeof(char)*4);
4、free function
grammar :void free(void *ptr);
char * ptr;
ptr = (char *)malloc(sizeof(char)*4);
free(ptr);
Memory leak problem
1、 Implicit memory leaks :malloc The application memory is not released in time after it is used up
2、 Missing memory block address : Point the unique pointer to a memory block to another address , There was no one at that address until where , It can't be released
To avoid memory leaks ,malloc( Such as the function of applying for space ) And free Functions appear in pairs
边栏推荐
猜你喜欢

ambari集群扩容节点+扩容服务操作

Online software testing training institutions lemon class and itest AI platform achieves strategic cooperation

【全网首发】JVM性能问题的自动分析

Redis 源码分析-数据结构及实现(字典dict)

分布式存储-fastdfs

面渣逆袭:线程池夺命连环十八问,面试官直夸我

ETL工具——kettle实现简单的数据迁移

线上软件测试培训机构柠檬班与iTest.AI平台达成战略合作

Solutions for vscode terminal failure

BUUCTF web WarmUp
随机推荐
一次全面的性能优化,从5秒优化到1秒
List与Map
解决idea新建module 提示module xxxx does exitst
Distributed registry etcd
Use of log4j
Swagger配置与使用
用户态协议栈-基于netmap的UDP实现
Wechat applet learning notes
Is the software testing training of lemon class reliable? This successful case of counter attack from the training class tells you
mysql的事务
MySQL安装配置教程(超级详细)
[bug solution] org apache. ibatis. type. TypeException: The alias ‘xxxx‘ is already mapped to the value ‘xxx‘
C语言的指针函数
【AI】利用简单神经网络做动作识别——基于coco关键点
Switch user mode, privileged mode, global mode, port mode
Mapbox loads local offline terrain
UML (use case diagram, class diagram, object diagram, package diagram)
MySQL 查询当天、本周,本月、上一个月的数据
性能瓶颈查找-火焰图分析
H5 how to obtain intranet IP and public IP