当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
二叉树的先序、中序、后序遍历
ArcMap 创建常量栅格并镶嵌至新栅格
聊聊并发编程的12种业务场景
Three methods for cesium to obtain the longitude and latitude at the mouse click
Excel calculates the remaining days of the month
What are the B domain, m domain and O domain
Is the cookie valid for a limited time? How to set cookies? Teach you to set by hand
分布式注册中心-etcd
Redis source code analysis dynamic string implementation (SDS)
基于PaddleOCR解决文本检测训练模型与inference模型预测效果不一致的问题
MySQL学习笔记(4)——(基本CRUD)操作数据库中的表的数据
C语言的指针函数
Performance bottleneck finding - Flame graph analysis
9.数据仓库搭建之DIM层搭建
ambari 2.7.5集成安装hue 4.6
Online software testing training institutions lemon class and itest AI platform achieves strategic cooperation
Nacos configuration management
一次全面的性能优化,从5秒优化到1秒
A comprehensive performance optimization, from 5 seconds to 1 second
redis 源码分析3 间断遍历的实现









