导入
在堆区上开辟数据 然乎最后最好必须的释放堆区
序号 | 函数和描述 |
1 | *void \calloc(需要多少个单元, 每个单元占所占空间); |
2 | void free(一个接收动态内存的指针;) |
3 | **void \*malloc(需求多少内存空间);**他会在堆区建立内存 |
4 | *void \realloc(接收动态内存的地址, 增加到多少内存空间); |
GNU 认为 void \* 和 char \* 一样,所以以下写法是正确的:
ptr = (char *)malloc( 20 * sizeof(char) ); ptr =malloc( 20 * sizeof(char) ); ptr =calloc(20, sizeof(char)); ptr =(char *)calloc(20, sizeof(char)); //都可以分配
calloc()
void *calloc(size_t nitems, size_t size)
返回一个指向堆区的指针
void *calloc(参数1, 参数2)
void * 在你写内存分配的时候,最好强制类型转化一下,好比int*,char*
参数1:有多少个数据
参数2:每个数据的占位空间,sizeof(int)...
原始初始化问题,数组了calloc后,堆区的数都会被初始化位0
而超过堆区的数据不hi被初始化为0
如果你把堆区的数据个数写超过了也没事,至少我没有发现什么差错
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int i=0;
ptr=(int*)calloc(10,4);
puts("输入");
for(i=0;i<3;i++)
scanf("%d",&ptr[i]);
puts("输出");
for(i=0;i<20;i++)
printf("%d ",ptr[i]);
//这里我们输出15个,看看堆区初始化的数据是什么
free(ptr);
return 0;
}
输出
输入
1
2
3
输出
1 2 3 0 0 0 0 0 0 0 0 0 -1552596469 -1552596469 -1424274686 11985280 8323298 14082472 14082472 14082472
如果你写入15个数字 输出
输入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1055062760 1056193909 1048771264 1048771264 1048771264
可以看到数据还是被写进去了
malloc()
看汇编,一层一层的调用
malloc _nh_malloc_dbg | _heap_alloc_dbg | _heap_alloc_base | HeapAlloc |
与calloc
的功能差不多
malloc 和 calloc 之间的不同点是,malloc 不会设置内存为零,而 calloc 会设置分配的内存为零。
检验后发现不是那样
void *malloc(size_t size)
参数是一个 总空间大小,个数*大小 返回指向动态内存的指针
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int i=0;
ptr=(int*)malloc(4*10);
puts("输入");
for(i=0;i<3;i++)
scanf("%d",&ptr[i]);
puts("输出");
for(i=0;i<20;i++)
printf("%d ",ptr[i]);
//这里我们输出15个,看看堆区初始化的数据是什么
free(ptr);
return 0;
}
控制台窗口
输入
1
2
3
输出
1 2 3 0 0 0 0 0 0 0 0 0 -1850975387 -1850975387 -1715318164 846199022 848682877 839907526 839907526 839907526
realloc()
void *realloc(void *ptr, size_t size)
void *realloc(参数1, 参数2) 返回新的指针,不过还是一样的 如果请求失败,则返回 NULL。 参数1:已存在的内存块存指针 参数2:重置到多大的空间
free()
看汇编,一层一层的调用
free | _free_dbg | _free_base | HeapFree | |
释放堆区
有些堆区的地址指着可能你搞不见了,这时候你也要想到去释放
new/delete
int *x=new int(5);//创建4字节的堆区,初始化为5
int* x=new int //创建4字节的堆区
struct me* tmp=new struct me(1,2); //创建一个结构体,然后调用有参构造
int* arr=new int[5]; 创建
delete[] arr; 删除
对于new出来的数组,delete的本质是循环delete