简介malloc()和free()
malloc()简介
C语言声明变量等都是在内存上开辟空间的,内存包括四个区域:代码区,数据区,堆区和栈区。
一般的声明都是在栈帧中开辟空间的,在windows系统中,栈区一般是1M大小,而C语言可以在程序运行时分配更多的空间,主要工具是malloc(),此函数会在堆区中申请空间。在头文件stdlib.h中。
该函数接受一个参数:所需内存的字节数,它返回动态分配内存块的首地址。这个指针指向void,相当于泛型指针,所以通常该返回值会要被强制转换为匹配的类型。
例如:
#include<stdlib.h>
int* ptr = (int*)malloc(sizeof(int));
通常malloc()和free()配对使用。
free()函数的参数是之前malloc()返回的地址,该函数释放之前malloc()分配的内存。
例如使用malloc()实现一个数组的内存分配:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
const int SIZE = 10;
int i = 0;
int* ptr = (int*)malloc(SIZE * sizeof(int));
if (ptr == nullptr) //malloc()可能分配不到所需内存
{ //在这种情况下,让函数返回空指针
printf("Memory allocation failed.\n");
exit(EXIT_FAILURE); //程序结束
}
puts("Please enter the values(q to quit):");
while (i < SIZE && scanf_s("%d", &ptr[i]) == 1) //初始化数组
++i;
for (i = 0; i < SIZE; ++i) //输出数组的元素
{
printf("%5d", ptr[i]);
}
printf("\n");
free(ptr);
ptr = nullptr;
return 0;
}
free()的重要性
如果在使用完malloc()后忘掉free(),当函数结束时,作为自动变量的指针也会消失,但是它所指向的申请的内存依然存在,指针被销毁,那这块内存也无法访问,导致不能被重复利用。
calloc()函数
和malloc()函数类似
其格式为:
int* ptr = (int*) calloc(10, sizeof(int));