动态内存管理

1、动态内存的作用

常规的内存管理方式有两种

1. int val = 20;   //在栈空间上开辟四个字节

2. char arr[10] = {0};  //在栈空间上开辟十个字节的连续空间

但这样开辟空间的方法有两个弊端

一:空间开辟大小固定

二:数组开辟空间必须指明大小,且开辟后不能更改

当我们需要的空间大小在程序运行的时候才能知道,那数组的编译时开辟空间的方式就不能满足了。这时候就需要引用动态内存管理来自己申请和释放内存。

2、malloc和free

2.1、malloc

c语言提供的一个开辟动态内存的函数。函数原型如下:

void* malloc(size_t size);

声明在 stdlib.h 头文件中

这个函数向内存申请⼀块连续可用的空间,并返回指向这块空间的指针。

malloc函数申请的空间是在内存的堆区(calloc和realloc申请的空间也在内存的堆区)

·如果开辟成功,则返回一个指向开辟好的空间的指针。

·如果开辟失败,则返回一个 NULL 指针,因此malloc的返回值一定要做检查。

·返回值的类型是 void* ,所以malloc函数并不知道开辟空间的类型,具体由使用的情况决定。

·如果参数size为0,malloc的行为是标准未定义的,取决于编译器。

int main()
{
int* p = (int*)malloc(10*sizeof(int));
if (p == NULL)
  {
	perror("malloc");
 	return 1;
  }
int i = 0;
for (i = 0; i < 10; i++)
  {
	*(p + i) = i;
  }
for (i = 0; i < 10; i++)
  {
	printf("%d ", *(p + i));
  }
}

2.2、free

c语言提供了另一个专门用来做动态内存的释放和收回的函数free。函数原型如下:

void free(void* ptr);

声明在 stdlib,h 头文件中。

free函数用来释放动态开辟的内存。

·如果参数ptr指向的空间不是动态开辟的,那free函数的行为是未定义的。

·如果参数ptr是 NULL 指针,则函数不会进行任何处理。

总结,malloc和free的使用

int main()
{
int* p = (int*)malloc(10*sizeof(int));
if (p == NULL)
  {
	perror("malloc");
 	return 1;
  }
int i = 0;
for (i = 0; i < 10; i++)
  {
	*(p + i) = i;
  }
for (i = 0; i < 10; i++)
  {
	printf("%d ", *(p + i));
  }

//释放空间
free(p);
p = NULL;

return 0;
}

代码中 p = NULL; 的语句具有必要的意义,当我们使用free释放内存空间时,只是将空间还给系统,但是指针p仍记录这开辟的空间的起始地址,这样会造成指针p成为野指针,因此我们需要把p指为空指针

3、calloc和realloc

3.1、calloc

c语言还提供了一个函数叫calloccalloc函数也用来动态内存分配。原型如下:

void* calloc(size_t num,size_t size);

·函数的功能是为num个大小为size的元素开辟一块空间,并且把每个空间的每个字节初始化为0;

·与函数malloc的区别只在于calloc会在返回地址之前把申请的空间的每个字节初始化为全0。

区别如下:

当我们不对malloc创建的动态空间赋值时,打印出的是乱码,这和函数栈帧的创建和销毁有关。

#include <stdio.h>
#include <stdlib.h>

int main()
{
	int* p = (int*)malloc(10 * sizeof(int));
	if (p == NULL)
	{
		perror("malloc");
		return 1;
	}
	int i = 0;
	//for (i = 0; i < 10; i++)
	//{
	//	*(p + i) = i;
	//}
	for (i = 0; i < 10; i++)
	{
		printf("%x ", *(p + i));
	}

	//释放空间
	free(p);
	p = NULL;

	return 0;
}

当我们不对malloc创建的动态空间赋值时,打印的全是0。

#include <stdio.h>
#include <stdlib.h>

int main()
{
	//int* p = (int*)malloc(10 * sizeof(int));
	int* p = (int*)calloc(10, sizeof(int));
	if (p == NULL)
	{
		perror("malloc");
		return 1;
	}
	int i = 0;
	//for (i = 0; i < 10; i++)
	//{
	//	*(p + i) = i;
	//}
	for (i = 0; i < 10; i++)
	{
		printf("%x ", *(p + i));
	}

	//释放空间
	free(p);
	p = NULL;

	return 0;
}

3.2、realloc

·c语言提供的realloc函数让动态内存空间管理更加灵活。

·当我们感觉过去申请的空间过大或过小时就可以使用realloc函数对动态开辟内存的大小进行调整。

函数类型如下:

void* realloc(void* ptr,size_t size);

·ptr是调整的内存地址

·size是调整之后的新大小

·返回值为调整之后的内存起始位置

·这个函数调整原内存空间大小的基础上,还会将原来内存中的数据移动到新空间。

realloc调整空间情况:

1、调整空间失败,返回NULL。(说明realloc不能用p来接受返回值,应该用指针接受)

2、调整空间成功存在两种情况:

 情况1:在已经开辟好的空间后面,没有足够的空间直接进行空间的扩大,这种情况下,realloc会在内存的堆区重新找一个空间(满足新的空间的大小需求),同时会把旧的数据拷贝到新的空间,然后释放旧的空间,同时返回新的空间的起始地址。

 情况2:在已经开辟好的空间后面,有足够的空间,直接进行扩大,扩大空间后直接返回旧的空间的起始地址。

此外,realloc函数除了能调整空间之外,它还能实现和malloc一样的功能。

int main()
{
   int* p = (int*)realloc(NULL,40);
 
   free(p);
   p=NULL;
}

int* p = (int)realloc(NULL,40); //此时等价于malloc

注:malloc/calloc/realloc 申请的空间

如果不主动释放,出了作用域是不会销毁

释放的方式是:

1、free主动释放

2、直到程序结束,才由操作系统回收

4、常见的动态内存的错误

4.1、对NULL指针的解引用操作

void test()
{
   int* p = (int*)malloc(100);
   *p = 20;
   free(p);
}

这里的 p 的值可能是NULL,就会导致代码出现问题。

因此需要对 p 进行判断:

void test()
{
   int* p = (int*)malloc(100);
   if(p == NULL)
   {
      perror("malloc");
      return 1;
   }
   *p = 20;
   free(p);
   p = NULL;
}

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

void test()
{
   int* p = (int*)malloc(40);
   if(p = NULL)
   {
      return 0;
   }
   int i=0;
   for(i=0;i<=10;i++)
   {
      *(p+i) = i;
   }
   
   free(p);
   p = NULL;
}

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

void test()
{
   int a = 10;
   int* p = (int*)malloc(40);
   *p = &a;//此时指针p指向a
   free(p);
}

这里p指向了a,对非动态开辟内存使用free释放时错误的,此外,没有对malloc申请的动态内存进行释放,这样会导致内存泄露。

4.4、使用free释放动态内存的一部分

void test()
{
   int *p = (int *)malloc(100);
   p++;
   free(p);//p不再指向动态内存的起始位置
}

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

void test()
{
   int *p = (int *)malloc(100);
   free(p);
   free(p);//重复释放
}

4.6、动态开辟内存忘记释放(内存泄露)

void test()
{
   int *p = (int *)malloc(100);
   if(NULL != p)
   {
   *p = 20;
   }
}
int main()
{
   test();
   while(1);
}

忘记释放不再使用的动态开辟的空间会造成内存泄漏。

:动态开辟的空间⼀定要释放,并且正确释放。

还有一种常见的没有对动态开辟的空间进行释放造成内存泄露的情况。提前跳出函数。

void test()
{
   int* p = (int*)malloc(40);
   if(NULL != p)
   {
       return;
   }
   free(p);
   p = NULL;
}

int main()
{
   test();
   return 0;
}

5、动态内存经典笔试题分析

5.1、题目一

void GetMemory(char *p)
 {
    p = (char *)malloc(100);
 }
void Test(void)
 {
    char *str = NULL;
    GetMemory(str);
    strcpy(str, "hello world");
    printf(str);
 }

请问Test函数会有什么样的结果?

分析:str是NULL指针,通过GetMemory函数传给指针p,再往下走p指向了malloc开辟的动态内存空间的起始地址,但函数传参时,形参是实参的临时拷贝,因此str依然是NULL指针,strcpy中使用了str,就是对NULL指针解引用操作,造成非法访问,程序崩溃。此外,没有对动态内存释放,也会造成内存泄漏。

改正

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;
 }

void GetMemory(void)
 {
    char *p = (char *)malloc(100);
    return p; 
}
void Test(void)
 {
    char *str = NULL;
    str = GetMemory();
    strcpy(str, "hello world");
    printf(str);
    free(str);
    str = NULL;
 }

5.2、题目二

char *GetMemory(void)
{
    char p[] = "hello world";
    return p;
}
void Test(void)
{
    char *str = NULL;
    str = GetMemory();
    printf(str);
}

请问Test函数会有什么样的结果?

分析:这是典型的返回栈空间地址问题。p虽然能够将地址传给str,但p所开辟的空间再离开GetMemory后被销毁,此时str成为了野指针。从函数栈帧的角度来看,p的空间被销毁,此时如果printf一块空间,就有可能将p被销毁的空间覆盖,此时str有可能是随机值。

改正:只需用static让p不被销毁即可

5.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);
}

请问Test函数会有什么样的结果?

分析:存在内存泄漏,没有释放动态空间。

改正

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(str);
    str = NULL;
}

5.4、题目四

void Test(void)
{
    char *str = (char *) malloc(100);
    strcpy(str, "hello");
    free(str);
    if(str != NULL)
    {
    strcpy(str, "world");
    printf(str);
    }
}

请问Test函数会有什么样的结果?

分析:free(str)后str是野指针,strcpy对str解引用会造成非法访问。

改正:在 free(str); 后加上 str  = NULL;

6、柔性数组

结构体最后一个元素允许是未知大小的数组,这就叫 柔性数组 成员

typedef struct st_type
{
    int i;
    int a[];
}type_a;

其中的   int a[];   就是柔性数组成员。

6.1、柔性数组的特点

1.结构中的柔性数组成员前必须有至少一个其他成员。

2.sizeof返回的这个 结构大小不包括柔性数组的内存。

3.包含柔性数组成员的结构用malloc函数进行内存的动态分配,并且结构分配的内存应该大于结构的大小,以适应柔性数组的预期大小。

6.2、柔性数组的应用

struct St
{
    char c;
    int n;
	int arr[0];//
};


int main()
{
    struct St s = {0};
	printf("%d\n", sizeof(struct St));
	struct St* ps = (struct St*)malloc(sizeof(struct St) + 10 * sizeof(int));
	if (ps == NULL)
	{
		perror("malloc");
		return 1;
	}
	ps->c = 'w';
	ps->n = 100;
	int i = 0;
    for (i = 0; i < 10; i++)
    {
	ps->arr[i] = i;
	}
	//数组空间不够
	struct St* ptr = realloc(ps, sizeof(struct St) + 15 * sizeof(int));
	if (ptr != NULL)
	{
		ps = ptr;
	}
	else
	{
		perror("realloc");
		return 1;
	}
	//...继续使用

	for (i = 10; i < 15; i++)
	{
		ps->arr[i] = i;
	}

	for (i = 0; i < 15; i++)
	{
		printf("%d ", ps->arr[i]);
	}
	printf("\n%d\n", ps->n);
	printf("%c\n", ps->c);



	//释放
	free(ps);
	ps = NULL;

	return 0;
}

6.3、柔性数组的优点

truct St
{
	char c;
	int n;
	int* arr;
};


int main()
{
	//struct St s = {0};
	//printf("%d\n", sizeof(struct St));
	struct St* ps = (struct St*)malloc(sizeof(struct St));
	if (ps == NULL)
	{
		perror("malloc");
		return 1;
	}
	ps->c = 'w';
	ps->n = 100;
	
	ps->arr = (int*)malloc(10*sizeof(int));
	if (ps->arr == NULL)
	{
		perror("malloc-2");
		return 1;
	}
	//使用
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		ps->arr[i] = i;
	}

	//数组空间不够
	int* ptr = (int*)realloc(ps->arr, 15*sizeof(int));
	if (ptr == NULL)
	{
		perror("realloc");
		return 1;
	}
	else
	{
		ps->arr = ptr;
	}
	//使用
	for (i = 10; i < 15; i++)
	{
		ps->arr[i] = i;
	}
	for (i = 0; i < 15; i++)
	{
		printf("%d ", ps->arr[i]);
	}
	printf("\n%d\n", ps->n);
	printf("%c\n", ps->c);

	//释放
	free(ps->arr);
	ps->arr = NULL;

	free(ps);
	ps = NULL;

	return 0;
}

和上面的代码相比,柔性数组有利于内存释放和访问速度。

  • 17
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值