动态内存的开辟是在堆区进行内存空间的开辟,开辟到的是一块连续的空间
malloc - 不初始化
calloc - 初始化为0
realloc - 调整内存空间的大小的/如果第一个参数是NULL,功能类似malloc
free - 释放动态开辟的内存空间的
malloc的使用
#include<stdio.h>
#include<string.h>
#include<errno.h>
int main() {
//malloc返回的是空指针,所以要把他转换成对应的指针类型
//int* p = (int*)malloc(40);
int* p = (int*)malloc(INT_MAX);
int* ptr=p;
if (p == NULL) {
printf("%s", strerror(errno));
return 1;
}
//使用
for(int i=0;i<10;i++){
*ptr=i;
ptr++;
}
//释放
free(p);
p=NULL;//不把p置为空指针,p就变成了野指针
return 0;
}
calloc的使用
int main() {
int* p = calloc(10, sizeof(int));//10是开辟的个数,
//后面是开辟每个个数需要的空间
if (p == NULL) {
perror("calloc");
return 1;
}
//使用
for (int i = 0; i < 10; i++) {
*(p + i) = i;
}
//释放
free(p);
p = NULL;
return 0;
}
realloc的使用
int main() {
int* p = (int*)malloc(40);
if (p == NULL) {
return 1;
}
//使用
for (int i = 0; i < 10; i++) {
*(p + i) = i;
}
//增加空间
int* ptr = (int*)realloc(p,80);//p是起始地址,80是开辟空间的大小
if (ptr != NULL){
p = ptr;
ptr=NULL;
}
//当realloc开辟失败返回的是null
//释放
free(p);
p = NULL;
}