前言
- 动态内存都是在堆区上开辟的
一、学习动态内存函数
malloc和free
代码
#include <stdio.h>
#include <stdlib.h>
//malloc 返回类型void 不会初始化
int main()
{
int arr[10];
int* p = (int*)malloc(40);
if(p==NULL)
{
perror("malloc");
return 1;
}
//开辟成功
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d\n", *(p + i));
}
free(p);
return 0;
}
calloc
#include <stdio.h>
#include <stdlib.h>
//calloc
//会初始化
int main()
{
int* p = (int*)calloc(10, sizeof(int));
if(p==NULL)
{
perror("malloc");
return 1;
}
//开辟成功
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d\n", *(p + i));
}
free(p);
p = NULL;
return 0;
}
realloc
#include <stdio.h>
#include <stdlib.h>
//realloc
int main()
{
int* p = (int*)malloc(40);
if (p == NULL)
{
perror("malloc");
return 1;
}
//初始化为1~10
int i = 0;
for (i = 0; i < 10; i++)
{
p[i] = i + 1;
}
//增加一下空间
int* ptr = (int*)realloc(p, 80);//不会初始化
if (ptr != NULL)
{
p = ptr;
ptr = NULL;
}
else
{
perror("realloc");
return 1;
}
//打印数据
for (i = 0; i < 20; i++)
{
printf("%d\n", p[i]);
}
//释放
free(p);
p = NULL;
return 0;
}
二、常见的动态内存管理错误
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
//3.1 对NULL指针的解引用操作
void test()
{
int* p = (int*)malloc(INT_MAX / 4);
*p = 20;
}
int main()
{
test();
return 0;
}
//3.2 对动态内存开辟空间的越界访问
int main()
{
int* p = (int*)malloc(40);
if (p == NULL)
{
perror("malloc");
return 1;
}
int i = 0;
for (i = 0; i < 20; i++)
{
printf("%d\n", p[i]);
}
free(p);
p = NULL;
return 0;
}
//3.3 对非动态开辟内存使用free释放
int main()
{
int a = 0;
int* p = &a;
free(p);
p = NULL;
return 0;
}
//3.4使用free释放一块动态内存的一部分
int main()
{
int* p = (int*)malloc(40);
//int* ptr = p; 修正
if (p == NULL)
{
perror("malloc");
return 1;
}
int i = 0;
for (i = 0; i < 5; i++)
{
*p = i;
p++;
}
//p = ptr;修正
//释放
free(p);
p = NULL;
return 0;
}
//3.5 对同一块空间的多次释放
int main()
{
int* p = (int*)malloc(40);
if (p == NULL)
{
perror("malloc");
return 1;
}
//使用
//释放
free(p);
//p = NULL;修正
//多次释放
free(p);
return 0;
}
//3.6 动态内存开辟忘记释放(内存泄漏)
void test()
{
int* p = (int*)malloc(100);
if (p == NULL)
{
perror("malloc");
}
else
{
*p = 20;
}
//free(p);修正
//p = NULL;
}
int main()
{
test();
while (1);
return 0;
}
三、柔性数组
struct S
{
int a;
int arr[];//柔性数组
};
总结
- 就这样简单的把核心知识点梳理一遍