动态内存管理

1. 为什么要有动态内存分配

我们已经学习的内存开辟⽅式有:

cpp 复制代码
int val = 20;//在栈空间上开辟四个字节
char arr[10] = {0};//在栈空间上开辟10个字节的连续空间

但是上述的开辟空间的⽅式有两个特点:
1️⃣空间开辟⼤⼩是固定的。
2️⃣数组在申明的时候,必须指定数组的⻓度,数组空间⼀旦确定了⼤⼩不能调整但是对于空间的需求,不仅仅是上述的情况.有时候我们需要的空间⼤⼩在程序运⾏的时候才能知道,那数组的编译时开辟空间的⽅式就不能满⾜了.
C语⾔引⼊了动态内存开辟,让程序员⾃⼰可以申请和释放空间,就⽐较灵活了.

2. malloc和free

2.1 malloc

C语⾔提供了⼀个动态内存开辟的函数:

cpp 复制代码
void* malloc (size_t size);//size指定的大小的,单位是字节

这个函数向内存(堆区)申请⼀块连续可⽤的空间,并返回指向这块空间的指针.
1️⃣如果开辟成功,则返回⼀个指向开辟好空间的指针.
2️⃣如果开辟失败,则返回⼀个 NULL 指针,因此malloc的返回值⼀定要做检查.
3️⃣返回值的类型是 void* ,所以malloc函数并不知道开辟空间的类型,具体在使⽤的时候使⽤者⾃
⼰来决定.
4️⃣如果参数 size 为0,malloc的⾏为是标准是未定义的,取决于编译器.

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
//向内存申请40个字节的空间,用来存放整型数据
int arr[10];//栈区
int* p = (int*)malloc(INT_MAX*1000);
if (p == NULL) //空间申请失败
{
perror("malloc");
return 1;//异常返回
}
return 0;//表示正常返回
}
//当你指定大小过大时,内存就没有足够的空间了

2.2 free

C语⾔提供了另外⼀个函数free,专⻔是⽤来做动态内存的释放和回收的,函数原型如下:

cpp 复制代码
void free (void* ptr);//释放的是ptr指向的空间
                      //ptr中存放的是要释放的空间的起始地址

free函数⽤来释放动态开辟的内存.
1️⃣如果参数ptr指向的空间不是动态开辟的,那free函数的⾏为是未定义的.
2️⃣如果参数ptr是NULL指针,则函数什么事都不做.
malloc和free都声明在 stdlib.h 头⽂件中.

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
//向内存申请40个字节的空间,用来存放整型数据
int arr[10];//栈区
	int* p = (int*)malloc(40);
	if (p == NULL) //空间申请失败
    {
		perror("malloc");
		return 1;//异常返回
	}
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		*(p + i) = i + 1;	
}
	for (i = 0; i < 10; i++)

	{
	printf("%d ", p[i]);
	}
	free(p);//这里是free函数是主动释放内存空间,如果说没有写free函数
            //当程序运行结束时,操作系统会主动回收这些内存空间的
	p = NULL;
    return 0;
}
cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num = 0;
scanf("%d", &num);
int arr[] = {0};
int* ptr = NULL;
ptr = (int*)malloc(num*sizeof(int));
if(NULL != ptr)//判断ptr指针是否为空
{
int i = 0;
for(i=0; i<num; i++)
{
*(ptr+i) = 0;
}
}
free(ptr);
ptr = NULL;
return 0;
}

3. calloc和realloc

3.1 calloc

C语⾔还提供了⼀个函数叫calloc ,calloc函数也⽤来动态内存分配.原型如下:

cpp 复制代码
void* calloc (size_t num, size_t size);

1️⃣函数的功能是为 num个⼤⼩为 size的元素开辟⼀块空间,并且把空间的每个字节初始化为0.
2️⃣与函数 malloc 的区别只在于calloc 会在返回地址之前把申请的空间的每个字节初始化为全0.

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p = (int*)calloc(10, sizeof(int));
if(NULL != p)
{
int i = 0;
for(i=0; i<10; i++)
{
printf("%d ", *(p+i));
}
}
free(p);
p = NULL;
return 0;
}


所以如果我们对申请的内存空间的内容要求初始化,那么可以很⽅便的使⽤calloc函数来完成任务.

3.2 realloc

realloc函数的出现让动态内存管理更加灵活.有时会我们发现过去申请的空间太⼩了,有时候我们⼜会觉得申请的空间过⼤了,那为了合理的使⽤内存,我们⼀定会对内存的⼤⼩做灵活的调整.那 realloc 函数就可以做到对动态开辟内存⼤⼩的调整.函数原型如下:

cpp 复制代码
void* realloc (void* ptr, size_t size);
//ptr指向的是要调整的内存空间
//ptr存放的是要调整的内存空间的起始地址
//size新空间的大小

1️⃣ptr是要调整的内存地址
2️⃣size调整之后新⼤⼩
3️⃣返回值为调整之后的内存起始位置
4️⃣这个函数调整原内存空间⼤⼩的基础上,还会将原来内存中的数据移动到新的空间.
5️⃣realloc在调整内存空间的是存在三种情况:
情况1:原有空间之后有⾜够⼤的空间
情况2:原有空间之后没有⾜够⼤的空间
情况3:就是扩容失败了,会返回NULL指针

情况1
当是情况1的时候,要扩展内存就直接原有内存之后直接追加空间,原来空间的数据不发⽣变化.
情况2
当是情况2 的时候,原有空间之后没有⾜够多的空间时,扩展的⽅法是:在堆空间上另找⼀个合适⼤⼩的连续空间来使⽤.这样函数返回的是⼀个新的内存地址.

cpp 复制代码
//由于上述的两种情况,realloc函数的使⽤就要注意⼀些。
#include <stdio.h>
#include <stdlib.h>
 int main()
 {
 int *ptr = (int*)malloc(100);
 if(ptr != NULL)
 {
 }
 else
 {
 return 1;
 }
 ptr = (int*)realloc(ptr, 1000);
 int*p = NULL;
 p = realloc(ptr, 1000);
 if(p != NULL)
 {
 ptr = p;
 }
 free(ptr);
 return 0;
 }

4. 常⻅的动态内存的错误

4.1 对NULL指针的解引⽤操作

cpp 复制代码
void test()
 {
 int *p = (int *)malloc(INT_MAX/4);
 *p = 20;//如果p的值是NULL,就会有问题
 free(p);
 }

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

cpp 复制代码
void test()
 {
 int i = 0;
 int *p = (int *)malloc(10*sizeof(int));
 if(NULL == p)
 {
 exit(EXIT_FAILURE);
 }
 for(i=0; i<=10; i++)
 {
 *(p+i) = i;//当i是10的时候越界访问
 }
 free(p);
 }
//动态开辟空间--申请的时候也是有大小的
得在自己的空间范围内使用,超出范围就是越界访问,就是非法访问

4.3 对⾮动态开辟内存使⽤free释放

cpp 复制代码
void test()
 {
 int a = 10;
 int *p = &a;
 free(p);
 }

4.4 使⽤free释放⼀块动态开辟内存的⼀部分

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

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

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

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

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

4.7malloc和free成对出现了,也可能出现内存泄漏

cpp 复制代码
void test()
{
 int* p = (int*)malloc(100);
 if (NULL != p)
{
 *p = 20;
}
 int n = 10;
 if (n > 0)
 return;
 free(p);
 p = NULL;
}

忘记释放不再使⽤的动态开辟的空间会造成内存泄漏。
切记:动态开辟的空间⼀定要释放,并且正确释放.

5. 动态内存经典笔试题分析(出自《高质量c/c++编程》)

5.1 题⽬1:

cpp 复制代码
 #include <stdio.h>
 #include <string.h>
 void GetMemory(char *p)
 {
 p = (char *)malloc(100);
 }
 void Test(void)
 {
 char *str = NULL;
 GetMemory(str);
 strcpy(str, "hello world");//str对NULL的解引用操作,程序就会崩溃,内存泄漏,代码中没有对malloc申请的空间释放
 printf(str);
 }
 int main()
{
  Test();
  return 0;
}
cpp 复制代码
 //正确的写法
 #include <stdio.h>
 #include <string.h>
 #include <cstdlib>
 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;
}

5.2 题⽬2:

cpp 复制代码
 #include <stdio.h>
 #include <string.h>
 char *GetMemory(void)
 {
 char p[] = "hello world";//p数组是函数的局部变量,出了函数,p数组的空间就回收了,回收了,p数组的内存就不可知了
 return p;
 }
 void Test(void)
 {
 char *str = NULL;
 str = GetMemory();
 printf(str);
 }
 int main()
{
 Test();
 return 0;
}
cpp 复制代码
 //正确的解法
 #include <stdio.h>
 #include <string.h>
 char *GetMemory(void)
 {
 static char p[] = "hello world";
 return p;
 }
 void Test(void)
 {
 char *str = NULL;
 str = GetMemory();
 printf(str);
 }
 int main()
{
 Test();
 return 0;
}

5.3 题⽬3:

cpp 复制代码
 #include <stdio.h>
 #include <string.h> 
 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;
}
cpp 复制代码
 #include <stdio.h>
 #include <string.h> 
 #include <cstdlib>
 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;
 }
 int main()
{
 Test();
 return 0;
}

5.4 题⽬4:

cpp 复制代码
 #include <stdio.h>
 #include <string.h>
 #include <cstdlib>
 void Test(void)
 {
 char *str = (char *) malloc(100);
 strcpy(str, "hello");
 free(str);//str置空变成野指针
 if(str != NULL)
 {
 strcpy(str, "world");
 printf(str);
 }
 }
 int main()
{
 Test();
 return 0;
}
cpp 复制代码
 //正确的解法 
 #include <stdio.h>
 #include <string.h>
 #include <cstdlib>
 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;
}

6. 柔性数组

也许你从来没有听说过柔性数组这个概念,但是它确实是存在的.
C99 中,结构中的最后⼀个元素允许是未知⼤⼩的数组,这就叫做『柔性数组』成员.

cpp 复制代码
//比如
struct st_type
 {
 int i;
int a[0];//柔性数组成员
};
cpp 复制代码
//有些编译器会报错⽆法编译可以改成
struct st_type
{
int i;
int a[];//柔性数组成员
};

6.1 柔性数组的特点:

1️⃣结构中的柔性数组成员前⾯必须⾄少⼀个其他成员.
2️⃣sizeof 返回的这种结构⼤⼩不包括柔性数组的内存.
3️⃣包含柔性数组成员的结构⽤malloc ()函数进⾏内存的动态分配,并且分配的内存应该⼤于结构的⼤⼩,以适应柔性数组的预期⼤⼩.包含柔性数组的结构体应该和动态内存分配的malloc函数配合使用

cpp 复制代码
typedef struct st_type
{
int i;
int a[0];//柔性数组成员
}type_a;
int main()
{
printf("%d\n", sizeof(type_a));//输出的是4
return 0;
}

6.2 柔性数组的使⽤

cpp 复制代码
//代码一
#include <stdio.h>
#include <stdlib.h>
int main()
{
 int i = 0;
 type_a *p = (type_a*);malloc(sizeof(type_a)+100*sizeof(int));
 p->i = 100;
 for(i=0; i<100; i++)
 {
 p->a[i] = i;
 }
 free(p);
 return 0;
 }//这样柔性数组成员a,相当于获得了100个整型元素的连续空间.

6.3 柔性数组的优势

上述的type_a 结构也可以设计为下⾯的结构,也能完成同样的效果.

cpp 复制代码
 //代码二 
 #include <stdio.h>
 #include <stdlib.h>
 typedef struct st_type
 {
 int i;
 int *p_a;
 }type_a;
 int main()
 {
 type_a *p = (type_a *)malloc(sizeof(type_a));
 p->i = 100;
 p->p_a = (int *)malloc(p->i*sizeof(int));
 for(i=0; i<100; i++)
 {
 p->p_a[i] = i;
 }
 free(p->p_a);
 p->p_a = NULL;
 free(p);
 p = NULL;
 return 0;
 }

上述代码1和代码2可以完成同样的功能,但是⽅法1的实现有两个好处:
第⼀个好处是:⽅便内存释放
1️⃣如果我们的代码是在⼀个给别⼈⽤的函数中,你在⾥⾯做了⼆次内存分配,并把整个结构体返回给⽤⼾.⽤⼾调⽤free可以释放结构体,但是⽤⼾并不知道这个结构体内的成员也需要free,所以你不能指望⽤⼾来发现这个事.所以,如果我们把结构体的内存以及其成员要的内存⼀次性分配好了,并返回给⽤⼾⼀个结构体指针,⽤⼾做⼀次free就可以把所有的内存也给释放掉.
第⼆个好处是:这样有利于访问速度.
2️⃣连续的内存有益于提⾼访问速度,也有益于减少内存碎⽚.(其实,我个⼈觉得也没多⾼了,反正你跑不了要⽤做偏移量的加法来寻址)

7. 总结C/C++中程序内存区域划分


C/C++程序内存分配的⼏个区域:
1️⃣栈区(stack):在执⾏函数时,函数内局部变量的存储单元都可以在栈上创建,函数执⾏结束时
这些存储单元⾃动被释放.栈内存分配运算内置于处理器的指令集中,效率很⾼,但是分配的内
存容量有限.栈区主要存放运⾏函数⽽分配的局部变量、函数参数、返回数据、返回地址等.
《函数栈帧的创建和销毁》
2️⃣堆区(heap):⼀般由程序员分配释放,若程序员不释放,程序结束时可能由OS(操作系统)
回收 .分配⽅式类似于链表.
3️⃣数据段(静态区):(static)存放全局变量、静态数据。程序结束后由系统释放.
4️⃣代码段:存放函数体(类成员函数和全局函数)的⼆进制代码。
以上就是今天的博客内容了,希望能够帮助到读者朋友们!

我们一起继续加油努力💪!一键三连🙏!!!

本篇完结,点赞收藏加关注,找到小编不迷路,感谢大家🙏🤝!

相关推荐
future_studio3 小时前
聊聊 Unity(小白专享、C# 小程序 之 播放器)
unity·小程序·c#
孤独得猿3 小时前
聊天室项目开发——etcd的安装和使用
linux·服务器·c++·etcd
new coder3 小时前
[c++语法学习]Day10:c++引用
开发语言·c++·学习
Narcissiffo3 小时前
【C语言】str系列函数
c语言·开发语言
helloworddm3 小时前
Orleans Stream SubscriptionId 生成机制详解
java·系统架构·c#
向宇it4 小时前
【unity实战】MapMagic 2实战例子
游戏·3d·unity·c#·游戏引擎
聪明的笨猪猪4 小时前
Java JVM “调优” 面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
hqyjzsb4 小时前
2025年市场岗位能力重构与跨领域转型路径分析
c语言·人工智能·信息可视化·重构·媒体·改行学it·caie
"菠萝"4 小时前
C#知识学习-017(修饰符_6)
学习·c#