动态内存管理

内容索引

  • 为什么存在动态内存分配
  • 动态内存函数的介绍
  1. malloc
  2. free
  3. calloc
  4. realloc
  • 常见的动态内存错误
  • 几个经典的笔试题
  • 柔性数组

为什么存在动态内存分配

我们已经掌握的内存开辟方式有:
int val = 20;//在栈空间上开辟四个字节
char arr[10] = {0};//在栈空间上开辟10个字节的连续空间
但是上述的开辟空间的方式有两个特点:
1. 空间开辟大小是固定的。
2. 数组在申明的时候,必须指定数组的长度,它所需要的内存在编译时分配。
但是对于空间的需求,不仅仅是上述的情况。有时候我们需要的空间大小在程序运行的时候才能知道, 那数组的编译时开辟空间的方式就不能满足了。
这时候就只能试试动态存开辟了。

动态内存函数的介绍

malloc和free

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

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

void free (void* ptr);
free 函数用来释放动态开辟的内存。
  • 如果参数 ptr 指向的空间不是动态开辟的,那free函数的行为是未定义的。(不需free)
  • 如果参数 ptr NULL指针,则函数什么事都不做。
mallocfree都声明在 stdlib.h 头文件中

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
int main()
{
	//申请
	int* p = (int*)malloc(20000);
	if (p == NULL)
	{
		printf("%s\n", strerror(errno));
		return 1;
	}
	//使用
	int i = 0;
	for (i = 0;i < 5;i++)
	{
		p[i] = i + 1;
	}
	for (i = 0;i < 5;i++)
	{
		printf("%d ", p[i]);
	}
	/*for (i = 0;i < 5;i++)
	{
		*(p + i) = i + 1;
	}
	for (i = 0;i < 5;i++)
	{
		printf("%d ", *(p + i));
	}*/
	
	//释放
	free(p);//不会把p置为空,要手动置为空
	p = NULL;//避免野指针

	return 0;
}

calloc

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

void* calloc (size_t num, size_t size);

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

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
int main()
{
	int* p = (int*)calloc(10, sizeof(int));
	if (p == NULL)
	{
		printf("calloc()-->%s\n", strerror(errno));
		return 1;
	
	}
	//使用
	int i = 0;
	for (i = 0;i < 10;i++)
	{
		printf("%d ", p[i]);
	}
	
	//释放
	free(p);
	p = NULL;
	return 0;
}

malloc和calloc的对比

1.参数不一样

2.都是在堆区上申请内存空间,但是malloc不初始化,calloc会初始化为0

如果要初始化,就使用calloc

不需要初始化,就可以使用malloc

realloc

realloc 函数的出现让动态内存管理更加灵活。
有时会我们发现过去申请的空间太小了,有时候我们又会觉得申请的空间过大了,那为了合理的时
候内存,我们一定会对内存的大小做灵活的调整。那 realloc 函数就可以做到对动态开辟内存大小
的调整。
函数原型如下:
void* realloc (void* ptr, size_t size);
  • ptr 是要调整的内存地址
  • size 调整之后新大小
  • 返回值为调整之后的内存起始位置
  • realloc 在调整内存空间的是存在两种情况: 
1.情况1 :原有空间之后有足够大的空间 
要扩展内存就直接原有内存之后直接追加空间,原来空间的数据不发生变化,realloc函数返回的是旧的地址

2. 情况2:原有空间之后没有足够大的空间

扩展的方法是:@1.realloc会找更大的空间

                         @2.将原来的数据拷贝到新的空间

                         @3.释放旧的空间

                         @4.返回新空间的地址

3.失败 返回空指针

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
int main()
{
	int* p = (int*)malloc(20);
	if (p == NULL)
	{
		printf("%s\n", strerror(errno));
		return 1;
	}
	//使用
	int i = 0;
	for (i = 0;i < 5;i++)
	{
		p[i] = i + 1;
	}
	int* ptr = (int*)realloc(p, 40);
	if (ptr != NULL)
	{
		p = ptr;
	}
	else
	{
		printf("realloc:%s\n", strerror(errno));
		return 1;
	}
	//使用
	for (i = 0;i < 10;i++)
	{
		p[i] = i + 1;
	}
	for (i = 0;i < 10;i++)
	{
		printf("%d ", p[i]);
	}
	//释放
	free(p);
	p = NULL;

	return 0;
}

常见的动态内存错误

NULL指针的解引用操作

int main()
{
	int* p = (int*)malloc(20);
	//可能会出现对NULL指针的解引用操作
	//所以malloc函数的返回值要判断的
	int i = 0;
	for (i = 0;i < 5;i++)
	{
		p[i] = i;
	}
	free(p);
	p = NULL;
	
	return 0;
}

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

int main()
{
	int* p = (int*)malloc(20);
	if (p == NULL)
	{
		printf("%s\n", strerror(errno));
		return 1;
	}
	//可能会出现对NULL指针的解引用操作
	//所以malloc函数的返回值要判断的
	int i = 0;
	//越界访问
	for (i = 0;i < 10;i++)
	{
		p[i] = i+1;
	}
	free(p);
	p = NULL;
	
	return 0;
}

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

int main()
{
	int arr[10] = { 1,2,3,4,5 };
	int* p = arr;
	//...
	free(p);
	p = NULL;
	return 0;
}

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

int main()
{
	int* p = (int*)malloc(20);
	if (p == NULL)
	{
		printf("%s\n", strerror(errno));
		return 1;
	}
	int i = 0;
	//[1] [2] [3] [4] [5] [] [] [] [] [] 
	for (i = 0;i < 5;i++)
	{
		*p = i + 1;
		p++;
	}
	//释放
	free(p);
	p = NULL;

	return 0;
}

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

int main()
{
	int* p = (int*)malloc(20);
	if (p == NULL)
	{
		return 1;
	}
	//使用
	//
	free(p);
	
	//释放
	free(p);
	p = NULL;
	return 0;
}

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

补充:

malloc calloc realloc 

所申请的空间,如果不想使用,需要free 释放

如果不使用free 释放

程序结束之后,也会由操作系统回收

如果不使用free 释放,程序也不结束

内存泄露

void test()
{
	int* p = (int*)malloc(20);
	//使用
	//存放 1 2 3 4 5
}

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

如何避免?

  1. 自己申请的,尽量自己释放
  2. 自己释放的,告诉别人释放

几个经典的笔试题

题目一

void GetMemory(char *p)
{
    p = (char *)malloc(100);
}
void Test(void)
{
    char *str = NULL;
    GetMemory(str);
    strcpy(str, "hello world");
    printf(str);
}
请问运行 Test 函数会有什么样的结果?

1.调用GetMemory函数的时候,str的传参为值传递,p是str的临时拷贝,所以在GetMemory函数内部将动态开辟空间的地址存放在p中的时候,不会影响str,所以GetMemory函数返回之后,str中依然是NULL指针。strcpy函数就会调用失败,原因是对NULL的解引用操作,程序会崩溃。

2.GetMemory函数内容malloc申请的空间没有机会释放,造成了内存泄露。

修改1:

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

修改2:

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;
}
int main()
{
    //char* p = "hehe\n";
    //printf("hehe\n");
    //printf("%s\n","hehe");

    return 0;
}

题目二

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

返回栈空间地址的问题

GetMemory函数内部创建的数组是临时的,虽然返回了数组的起始地址给了str,但是数组的内存出了GetMemory函数就被回收了,而str依然保存了数组的起始地址,这时如果使用str,str是野指针

同理的代码:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值