动态内存管理

为什么存在动态内存

#include<stdio.h>
main()
{
     int n=20;//在栈空间上开辟四个字节
     int arr[10]={0};//在栈空间上开辟10个字节的连续空间
}

在栈区开辟的空间有两个特点:

  1. 空间开辟大小是固定的。
  2. 数组在申明的时候,必须指定数组的长度,它所需要的内存在编译时分配。

但是对于空间的需求,不仅仅是上述的情况。有时候我们需要的空间大小在程序运行的时候才能知道,那数组的编译时开辟空间的方式就不能满足了。这时候就只能试试动态存开辟了。

动态内存函数介绍

malloc和free

void* malloc (size_t size);//不确定类型,返回类型为void*
//向内存申请一块连续可用的空间,并返回指向这块空间的指针。
  • 如果开辟成功,则返回一个指向开辟好空间的指针。
  • 如果开辟失败,则返回一个NULL指针,因此malloc的返回值一定要做检查。
  • 返回值的类型是 void* ,所以malloc函数并不知道开辟空间的类型,具体在使用的时候使用者自己来决定。
  • 如果参数 size 为0,malloc的行为是标准是未定义的,取决于编译器。
void free (void* ptr);

这里是free函数用来释放动态开辟的内存引用:

  • 如果参数 ptr 指向的空间不是动态开辟的,那free函数的行为是未定义的。
  • 如果参数 ptr 是NULL指针,则函数什么事都不做。
  • malloc和free都声明在 stdlib.h 头文件中。
#include<stdio.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
main()
{
	//申请40个字节,用来存放10个整形
	int* p = (int*)malloc(40);//malloc返回的是内存空间的首地址,类型是void类型,存放的是整形,用整形指针来接收,强制类型转换为整形指针
	if (p == NULL)//申请失败,返回空指针
	{
		printf("%s\n", strerror(errno));
		return 1;
	}
	//存放1-10
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		*(p + i) = i + 1;
	}
	for (i = 0; i < 10; i++)
	{
		printf("%d ", *(p+i));
	}
	//free释放申请的内存
	free(p);
	p = NULL;//释放完防止非法访问,主动为空指针
	return 0;
}

calloc

//calloc 函数也用来动态内存分配
void* calloc (size_t num, size_t size);
  • 函数的功能是为 num 个大小为 size 的元素开辟一块空间,并且把空间的每个字节初始化为0
  • 与函数 malloc 的区别只在于 calloc 会在返回地址之前把申请的空间的每个字节初始化为全0
#include<stdio.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
int main()
{
	int* p = (int*)calloc(10, sizeof(int));
	if (p == NULL)
	{
		printf("%s\n",strerror(errno));
		return 1;
	}
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		printf("%d ", *(p + i));
	}
	free(p);
	p = NULL;
	return 1;
}

在这里插入图片描述
总结:malloc申请到的空间,没有初始化直接返回起始地址。calloc申请好空间后,会把空间初始化为0然后返回起始地址。

realloc

  • realloc函数的出现让动态内存管理更加灵活
  • 有时会我们发现过去申请的空间太小了,有时候我们又会觉得申请的空间过大了,那为了合理的时
    候内存,我们一定会对内存的大小做灵活的调整。那 realloc 函数就可以做到对动态开辟内存大小
    的调整。
void* realloc (void* ptr, size_t size);
  • ptr 是要调整的内存地址
  • size 调整之后新大小
  • 返回值为调整之后的内存起始位置
  • 这个函数调整原内存空间大小的基础上,还会将原来内存中的数据移动到新的空间
  • realloc在扩容的时候失败,直接返回NULL
  • realloc当第一个参数为NULL指针时,其功能相当与realloc

realloc在调整内存空间的是存在两种情况:
情况1:原有空间之后有足够大的空间。
情况2:原有空间之后没有足够的大的空间
在这里插入图片描述
情况1:要扩展内存就直接原有内存之后直接追加空间,原来空间的数据不发生变化。
情况2:原有空间之后没有足够多的空间扩容时,realloc函数会找一个满足空间大小的新的连续空间,把旧的空间的数据,拷贝到新空间的前面的位置并且把旧的的空间释放掉,同时返回新的空间的地址

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
main()
{
	int* p = (int*)malloc(5 * sizeof(int));
	if (NULL == p)
	{
		perror("malloc");
		return 1;
	}
	int i = 0;
	for (i = 0; i < 5; i++)
	{
		*(p + i) = 1;
	}
	//内存不够,增加5个整形的空间
	int* ptr = (int*)realloc(p, 10 * sizeof(int));//使用一个新的指针来接收开辟内存的返回值
	//int* p = (int*)realloc(p, 10 * sizeof(int));不能使用p来接收开辟内存的返回值,如果开辟失败,会返回NULL类型的指针,会丢失前面的数据
	if (ptr != NULL)
	{
		p = ptr;
		ptr=NULL;
	}
	//继续使用空间
	for (i = 0; i < 10; i++)
	{
		printf("%d ", *(p + i));//空间扩大了,但没有赋值
	}
	free(p);
	p = NULL;
	return 0;
}

常见的动态内存错误

对NULL指针的解引用操作

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
int main()
{
	int* p = (int*)malloc(40);
	//malloc返回值一定要判断
	int i = 0;
	for (i = 0; i < 20; i++)
	{
		*(p + i) = 1;//如果p的返回值为NULL,*(p+i)会非法访问
	}
	return 0;
}

对动态开辟空间的越界访问

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
int main()
{
	int *p=(int *)malloc(100);
	if (p == NULL)
	{
		return 1;
	}
	int i = 0;
	//越界访问
	for (i = 0; i < 100; i++)
	{
		*(p + i) = 1;
	}
	free(p);
	p = NULL;
	return 0;
}
 

对非动态开辟内存使用free释放

//代码最终会挂掉
void test()
{
	int a = 10;//存放在栈区
	int* p = &a;
	free(p);
}
main()
{
	test();
}

使用free释放一块动态开辟内存的一部分

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
int main()
{
	int* p = (int*)malloc(100);
	if (p = NULL)
	{
		return 1;
	}
	int i = 0;
	for (i = 0; i < 25; i++)
	{
		*p = i;
		p++;
	}
	free(p);// p不再指向动态内存的起始位置
	p = NULL;
	return 0;
}

对同一块动态内存多次释放

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
int main()
{
	int* p = (int*)malloc(100);
	if (p == NULL)
	{
		return 1;
	}
	int i = 0;
	for (i = 0; i < 25; i++)
	{
		*(p + i) = 1;
	}
	free(p);
	free(p);
	return 0;
	//free两次解决办法:在第一次free完后将p赋值为NULL(p=NULL)
}

动态开辟内存忘记释放(内存泄漏)

#include<stdio.h>
#include<stdlib.h>
void test()
{
	int* p = (int*)malloc(100);
	if (NULL != p)
	{
		*p = 20;
	}
}
int main()
{
	test();
	while (1);
}
//忘记释放不再使用的动态开辟的空间会造成内存泄漏。
//解决办法:1.不想使用的时候,及时释放掉 2.函数内存进行了malloc操作,返回了malloc开辟的空间的起始地址,记得释放

几个经典题目

//题目1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void GetMemory(char* p)//str传给p的时候,p是str一份临时拷贝,p有自己的独立空间
{
	p = (char*)malloc(100);//申请的内存空间给到了指针p而p出了作用域就会销毁,str依然是NULL
                           //动态申请了内存,但是没有释放,会内存泄露
}
void Test(void)
{
	char* str = NULL;
	GetMemory(str);//值传递str指向的值是NULL,
	//GetMemory函数内部申请了空间后,地址放在p中时,str依然时NULL
	strcpy(str, "hello world"); //GetMemory函数返回之后, strcmp拷贝,形成了非法访问内存
	printf(str);
}
int main()
{
	test();
	return 0;
}
//修改方法
void GetMemory(char** p)
{
	*p = (char*)malloc(100);
}
void Test(void)
{
	char* str = NULL;
	GetMemory(&str);
	strcpy(str, "hello world");
	printf(str);
	free(str);
	str=NULL;
}
int main()
{
	Test();
	return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//题目2
//返回栈空间地址的问题
char* GetMemory(void)
{
	char p[] = "hello world";
	return p;//p所指向空间还给了操作系统
}
void Test(void)
{
	char* str = NULL;
	str = GetMemory();//str接收到了p返回的地址
	printf(str);//非法访问内存
}

int main()
{
	Test();
	return 0;
}
//解决方法
char* GetMemory(void)
{
	static char p[] = "hello world";
	return p;//p所指向空间还给了操作系统
}
void Test(void)
{
	char* str = NULL;
	str = GetMemory();//str接收到了p返回的地址
	printf(str);//非法访问内存
}

int main()
{
	Test();
	return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//题目3
void GetMemory(char** p, int num)
{
	*p = (char*)malloc(num);
}
void Test(void)
{
	char* str = NULL;
	GetMemory(&str, 100);
	strcpy(str, "hello");
	printf(str);//内存泄露//没有free
}
int main()
{
	Test();
	return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//题目4
void Test(void)
{
	char* str = (char*)malloc(100);
	strcpy(str, "hello");
	free(str);//提早free,提前还给了操作系统,str是一个野指针,非法访问
	if (str != NULL)
	{
		strcpy(str, "world");
		printf(str);
	}
}
int main()
{
	Test();
	return 0;
}
//解决方法:
void Test(void)
{
	char* str = (char*)malloc(100);
	strcpy(str, "hello");
	free(str);
	str=NULL;
	if (str != NULL)
	{
		strcpy(str, "world");
		printf(str);
	}
}
int main()
{
	Test();
	return 0;
}

c/c++程序的内存开辟

在这里插入图片描述
c/c++程序内存分配的几个区域:

  1. 栈区(stack):在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结
    束时这些存储单元自动被释放。栈内存分配运算内置于处理器的指令集中,效率很高,但是
    分配的内存容量有限。 栈区主要存放运行函数而分配的局部变量、函数参数、返回数据、返
    回地址等。
  2. 堆区(heap):一般由程序员分配释放, 若程序员不释放,程序结束时可能由OS回收 。分
    配方式类似于链表。
  3. 数据段(静态区)(static)存放全局变量、静态数据。程序结束后由系统释放。
  4. 代码段:存放函数体(类成员函数和全局函数)的二进制代码。

实际上普通的局部变量是在栈区分配空间的,栈区的特点是在上面创建的变量出了作用域就销毁。
但是被static修饰的变量存放在数据段(静态区),数据段的特点是在上面创建的变量,直到程序
结束才销毁所以生命周期变长。

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值