当前位置:网站首页>Allocate memory: malloc() and free()
Allocate memory: malloc() and free()
2022-07-29 05:28:00 【Ryan fitter】
Allocate memory :malloc() and free()
Memory storage categories have one thing in common : After determining which storage category to use , According to your own memory management rules , Scope and storage period will be automatically selected .
malloc() function
This function takes a parameter : Number of memory bytes required . use malloc() Create an array with the following code :
double * ptd;
ptd = (double *)malloc(30 * sizeof(double));
The above code is 30 individual double The value of type requests memory space , And set up ptd Point to this location . You can also use expressions ptd[0] Represents an array element .
Three ways to create arrays :
1. When you declare an array , The dimension of an array is represented by a constant expression , Use the array name to access the elements of the array . You can create this array with static memory or automatic memory .
2. When declaring a variable length array , The dimension of an array is represented by a variable expression , Use the array name to access the elements of the array . Arrays with this feature can only be created in automatic memory .
3. Declare a pointer , call malloc(), Assign its return value to the pointer , Using pointers to access elements of an array . The pointer can be static or automatic .
free() function
Usually malloc() To work with free() Matching use of . among free() The argument to the function is before malloc() Return address , Mainly to release malloc() Allocated memory . Call... At the end of the function free() Functions can avoid Memory leak The problem of
exit() function
If memory allocation fails , You can call exit() The function ends the program , Its prototype is also stdlib.h in , The standard provides two return values to ensure normal operation in all operating systems :
EXIT_SUCCESS( perhaps , amount to 0) Indicates the end of a normal program .
EXIT_FAILURE Indicates that the program aborts abnormally .
Other operating systems also accept integer values that indicate other operational errors .
Run a piece of code and use the above functions to realize the program :
// Assign arrays dynamically
#include <stdio.h>
#include <stdlib.h>// by malloc()、free() Provide prototypes
int main(void)
{
double * ptd;
int max;
int number;
int i = 0;
puts("What is the maxium nuber of type double enteries?");
if(scanf("%d",&max) != 1)
{
puts("Number not correctly entered -- bye.");
exit(EXIT_FAILURE);
}
ptd = (double *)malloc(max * sizeof(double));
if(ptd == NULL)
{
puts("Memory allocation failed. Goodbye.");
exit(EXIT_FAILURE);
}
//ptd Now point to max Array of elements
puts("Enter the Values (q to quit):");
while(i < max && scanf("%lf",&ptd[i]) == 1)
++i;
printf("Here are your %d enteries:\n", number = i);
for (i = 0; i < number;i++)
{
printf("%7.2f", ptd[i]);
if(i % 7 == 6)
putchar('\n');
}
if(i % 7 != 0)
putchar('\n');
puts("Done.");
free(ptd);
return 0;
}
Running results :
What is the maxium nuber of type double enteries?
5
Enter the Values (q to quit):
20 30 35 25 40 80
Here are your 5 enteries:
20.00 30.00 35.00 25.00 40.00
Done.
边栏推荐
- 【C语言系列】—三种方法模拟实现strlen库函数的方法
- 365 day challenge leetcode 1000 questions - day 042 array sequence number conversion + relative ranking discretization processing
- 直播预告:京东云DevOps与JFrog制品库的融合
- Live broadcast preview | how to improve enterprise immunity through "intelligent edge security"?
- 365天挑战LeetCode1000题——Day 040 设计跳表 + 避免洪水泛滥 + 查找大小为 M 的最新分组 + 销售价值减少的颜色球
- 【C语言系列】— 一道递归小题目
- 365 day challenge leetcode 1000 questions - day 037 elements and the maximum side length of squares less than or equal to the threshold + the number of subsequences that meet the conditions
- C语言函数实现输出I love you
- 京东云联合Forrester咨询发布混合云报告 云原生成为驱动产业发展新引擎
- Container security open source detection tool - veinmind (mirror backdoor, malicious samples, sensitive information, weak password, etc.)
猜你喜欢
365天挑战LeetCode1000题——Day 041 二分查找完结纪念 + 第 N 个神奇数字 + 在线选举
【C语言系列】—深度解剖数据在内存中的存储(二)-浮点型
Li Yan, CEO of parallel cloud: cloudxr, opens the channel to the metauniverse
C language handwritten qq-ai version
法线可视化
200 多家 ISV 入驻!阿里云计算巢发布一周年
QML control: combobox
研发效能|Kubernetes核心技术剖析和DevOps落地经验
科班同学真的了解未来的职业规划吗?
QT series - Installation
随机推荐
How rimworld uploads creative workshops through steamcmd
CryEngine3 调试Shader方法
数据泄漏、删除事件频发,企业应如何构建安全防线?
365天挑战LeetCode1000题——Day 041 二分查找完结纪念 + 第 N 个神奇数字 + 在线选举
数千个数据库、遍布全国的物理机,京东物流全量上云实录 | 卓越技术团队访谈录
Alibaba cloud architect details nine trends in the game industry
抽象类与接口
平行云CEO 李岩:CloudXR ,开启通往元宇宙的通道
Solution: find the position of the first and last element in a sorted array (personal notes)
携手数字人、数字空间、XR平台,阿里云与伙伴共同建设“新视界”
[event preview] cloud development, efficient and intelligent - the second Alibaba cloud ECS cloudbuild developer competition is about to start
水一篇图的拓扑排序
QT learning: qdropevent drag event
Xiaolu Inn - Trailer
C语言文件操作
Helm chart for Kubernetes
阿里云张新涛:异构计算为数字经济提供澎湃动力
Container security open source detection tool - veinmind (mirror backdoor, malicious samples, sensitive information, weak password, etc.)
365 day challenge leetcode 1000 questions - day 042 array sequence number conversion + relative ranking discretization processing
C语言宏#define命令练习