C 语言下的 malloc和 free 的最简单的例子
- C 语言的 malloc 和 free 的原理自行上网查。
- 环境: Windows 下的 VS 2015
- 注: 此文纯属是为了学习
<data structure>
时笔记,因为自己好久没碰 C 语言了,为了捡回这两个函数的用法,花了些时间。
用一个代码附上注释来解释标题的内容:
#include <stdlib.h> // malloc(), free()
#include <stdio.h>
#include <process.h> // exit()
// 声明空间的大小为 3
#define SIZE 3
int main() {
int *T;
// 使用 malloc() 申请空间
T = (int*)malloc(SIZE * sizeof(int));
// 判断是否申请成功,若申请失败,则提示退出
if (T == NULL) {
puts("failed......\n");
exit(1);
}
puts(" malloc success....");
// 给申请的空间赋值
for (int i = 0; i < SIZE; i++) {
T[i] = i;
}
// 打印值
for (int i = 0; i < SIZE; i++) {
printf("%d ", T[i]);
}
// 使用 free 释放空间
free(T);
return 0;
}
编译结果:
来源:哔哩哔哩 C 语言视频。