学习动态内存管理


前言

  • 动态内存都是在堆区上开辟的

一、学习动态内存函数

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[];//柔性数组  
};

总结

  • 就这样简单的把核心知识点梳理一遍
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值