1、介绍
3个函数都在<stdlib.h>头文件
1)、void* malloc(unsigned size);
在内存的动态存储区中分配一块长度为 size字节的连续区域,参数size为需要内存空间的长度, 返回该区域的首地址,这里我们需要主要如果申请失败返回 空指针
2)、void* realloc(void* ptr, unsigned newsize);
给一个 已经分配了地址的指针重新分配空间,参数ptr为原有的空间地址,newsize是重新申请的地址长度,地址可能会变
3)、void* calloc(size_t numElements, size_t sizeOfElement);
参数sizeOfElement为申请地址的单位元素长度,numElements为元素个数,即在内存中申请numElements*sizeOfElement字节大小的连续地址空间
会将所分配的内存空间中的每一位都初始化为零,也就是说,如果你是为字符类型或整数类型的元素分配内存,那么这些元素将保证 会被初始化为0
用完要记得释放内存
free(p);
p = NULL;
都在堆区分配内存,用完都需要释放,都是连续的分配内存
2、测试Demo
3个函数简单使用
#include <stdio.h> #include <stdlib.h> //malloc、realloc、calloc简单使用 int main() { int *p1 = NULL; p1 = malloc(10 * sizeof(int)); if (p1 != NULL) { //给p1赋值 for (int i = 0; i < 10; ++i) { *(p1 + i) = 5; } //打印值 for (int i = 0; i < 10; ++i) { printf("p1[%d] is %d\n", i, p1[i]); } free(p1); p1 = NULL; } int *p2 = NULL; p2 = calloc(5, sizeof(int)); if (p2 != NULL) { for (int i = 0; i < 5; i++) { printf("p2[%d] is %d\n", i, p2[i]); } free(p2); p2 = NULL; } char *p3, *q4; p3 = (char *)malloc(5); q4 = p3; p3 = (char *)realloc(p3, 10) if (p3 != NULL) { printf("p3 is %p\n", p3); printf("q3 is %p\n", q4); p3 = (char *)realloc(p3, 1000); printf("p3 is %p\n", p3); free(p3); p3 = NULL; } return 0; }
3、 运行结果
1111deMacBook-Pro:malloc a1111$ vim malloc.c 1111deMacBook-Pro:malloc a1111$ gcc -g malloc.c -o malloc 1111deMacBook-Pro:malloc a1111$ ./malloc p1[0] is 5 p1[1] is 5 p1[2] is 5 p1[3] is 5 p1[4] is 5 p1[5] is 5 p1[6] is 5 p1[7] is 5 p1[8] is 5 p1[9] is 5 p2[0] is 0 p2[1] is 0 p2[2] is 0 p2[3] is 0 p2[4] is 0 p3 is 0x7ff323c01020 q3 is 0x7ff323c01020 p3 is 0x7ff323c03260