🎉welcome to my blog |
请留下你宝贵的足迹吧(点赞👍评论📝收藏⭐) |
动态内存管理
1.引言
int n=10;//在栈空间上开辟4个字节
char c='w';//在栈空间上开辟1个字节
int val = 20;//在栈空间上开辟4个字节
char arr[10] = {0};//在栈空间上开辟10个字节的连续空间
上述的开辟空间的方式有两个特点:
• 空间开辟大小是固定的。
• 数组在申明的时候,必须指定数组的长度,数组空间⼀旦确定了大小就不能调整了
有时候我们需要的空间大小在程序运行时才能知道,数组在编译时开辟空间的方式就不能满足我们的需求了。 于是C语言引入了动态内存开辟,让程序员自己可以申请,释放空间,相对比较灵活。
2.动态内存开辟的函数
2.1.malloc
函数原型如下:
void* malloc (size_t size);//size单位是字节
这个函数向内存申请⼀块连续可用的空间,并返回指向这块空间的指针(即返回这块空间的起始地址)。
• 如果开辟成功,则返回⼀个指向开辟好空间的指针。
• 如果开辟失败,则返回⼀个 NULL 指针,因此malloc的返回值⼀定要做检查。
• 返回值的类型是 void* ,因为malloc函数并不知道开辟空间的类型,具体在使用的时候使用者自己来决定。
• 如果参数 size 为0,malloc的行为是未定义的,取决于编译器。
• 包含在头文件stdlib.h中
#include<stdio.h>
#include<stdlib.h>
int main()
{
//开辟20个字节的空间
//void* p = malloc(20);//这样写是不合适的,
//malloc申请的空间用来做什么是未知的,若申请的20个字节用来存放5个整型
//则应将其强制类型转化为int*,写法如下:
int* p = (int*)malloc(20);
if (p == NULL)
{
perror("malloc");//如果开辟失败则在malloc这报错
return 1;//直接返回
}
//如果开辟成功则可使用所开辟的空间
int i = 0;
for (i = 0; i < 5; i++)
{
*(p + i) = i + 1;//p为int* 类型的指针,p+i即跳过4*i个字节(即跳过i个整型),利用循环将5个整型变量赋值
}
return 0;
}
2.2 free
函数原型如下:
void free (void* ptr);
free函数用来释放动态开辟的内存。
• 要释放哪块空间就将哪块空间的起始地址传给free
#include<stdlib.h>
int main()
{
int* p = (int*)malloc(20);
if (p == NULL)
{
perror("malloc");
return 1;
}
int i = 0;
for (i = 0; i < 5; i++)
{//注意👀
//*(p + i) = i + 1;可讲此代码替换成以下代码
*p = i + 1;
p++;//但后面就不能用free(p)了,因为此时的p指向的不再是起始地址了
//而传给free的是所要释放空间的起始地址
}
free(p);//error
p = NULL;
return 0;
}
• 如果参数 ptr 指向的空间不是动态开辟的,那free函数的行为是未定义的。
• 如果参数 ptr 是NULL指针,则函数什么事都不做。
• 在头文件 stdlib.h 中声明
#include<stdlib.h>
int main()
{
//开辟20个字节 - 5个整型
int* p = (int*)malloc(20);
if (p == NULL)
{
perror("malloc");
return 1;
}
//使用空间
int i = 0;
for (i = 0; i < 5; i++)
{
*(p + i) = i + 1;
}
//释放空间
free(p);
p = NULL;
return 0;
}
2.3 calloc
原型如下:
void* calloc (size_t num, size_t size);
• 函数的功能是为 num 个大小为 size 的元素开辟⼀块空间,并且把空间的每个字节初始化为0
• 与函数 malloc 的区别只在于 calloc 会在返回地址之前把申请的空间的每个字节初始化为全 0
• 在头文件 stdlib.h 中声明
2.4 realloc
函数原型如下:
void* realloc (void* ptr, size_t size);
• realloc函数的出现让动态内存管理更加灵活
• 有时会我们发现之前申请的空间太小了,有时候我们又会觉得申请的空间过大了,为了合理的使用内存,我们需要对内存的大小做出灵活调整。C语言中realloc 函数可以实现对动态开辟内存大小的调整。
• ptr 是要调整的内存地址
• size 调整之后新大小
• 返回值为调整之后的内存起始位置
• 这个函数调整原内存空间大小的基础上,还会将原来内存中的数据移动到新的空间
• realloc在调整内存空间时存在两种情况:
◦ 情况1:原有空间之后有足够大的空间
◦ 情况2:原有空间之后没有足够大的空间
#include<stdio.h>
#include<stdlib.h>
int main()
{
//用malloc函数向内存申请5个int类型大小的空间
//将这5个整型变量中依次放入1 2 3 4 5
int* p = (int*)malloc(5 * sizeof(int));
if (p == NULL)
{
perror("calloc");
return 1;
}
//使用
int i = 0;
for (i = 0; i < 5; i++)
{
*(p + i) = i + 1;
}
//希望将空间调整为40个字节
//p=(int*)realloc(p, 40);//这样写是不靠谱的
//万一reallo函数调整失败就会返回NULL,那p就会变成空指针,之前的20个字节也没有了,风险有点大
//正确写法应如下
int* ptr = (int*)relloc(p, 40);
if (ptr != NULL)
{
p = ptr;
//如果调整成功就可以使用40个字节大小的空间了
int i = 0;
for (i = 5; i < 10; i++)
//这里只给新申请的后面5个整型变量赋值了
{
*(p + i) = i + 1;
}
for (i = 0; i < 10; i++)
{
printf("%d ", *(p + i));//打印
}
free(p);
p = NULL;
}
else
{
perror("relloc");
//如果调整失败还可以在这里使用之前20个字节大小的空间
//不想使用的话也可以free掉
free(p);
p = NULL;
return 1;
}
return 0;
}
注意👀:
#include<stdio.h>
#include<stdlib.h>
int main()
{
realloc(NULL, 20);//如果传给realloc函数空指针,由于无法申请空间
//realloc函数会申请新的空间,故realloc(NULL, 20);等价于malloc(20);
return 0;
}
3.常见动态内存的错误
3.1 对NULL指针的解引用操作
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int main()
{
int* p = (int*)malloc(INT_MAX*10);
*p = 20;//如果p的值是NULL,就会有问题
//正确做法应是先判断p是否为空指针(重要)
if (p == NULL)
{
perror("malloc");
return 1;
}
//以上判断代码等价于assert(p);
*p = 20;
return 0;
}
3.2对动态开辟空间的越界访问
#include<stdio.h>
#include<stdlib.h>
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);
}
int main()
{
test();
return 0;
}
3.3 对非动态开辟内存使用free释放
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a = 10;//a是普通的局部变量,在栈上不在堆上,不是动态申请的空间
int* p = &a;
//使用……
free(p);//free只能释放动态申请的空间
p = NULL;
return 0;
}
3.4 使用free释放⼀块动态开辟内存的⼀部分
#include<stdio.h>
#include<stdlib.h>
int main()
{
int* p = (int*)malloc(100);
if (p == NULL)
{
return 1;
}
int i = 0;
for (i = 0; i < 5; i++)
{
*p = i + 1;
p++;
}
free(p);//这里的p已不是所申请的动态内存空间的起始位置了
//因此不能用free释放空间了
p = NULL;
return 0;
}
3.5 对同⼀块动态内存多次释放
#include<stdio.h>
#include<stdlib.h>
void test()
{
int* p = (int*)malloc(100);
free(p);
free(p);//重复释放
//为避免以上重复释放可将第一次释放后的p置为空指针
}
int main()
{
test();
return 0;
}
3.6 动态开辟内存忘记释放(内存泄漏)
#include<stdio.h>
#include<stdlib.h>
void test()
{
int* p = (int*)malloc(100);
if (NULL != p)
{
*p = 20;//将20放入第一个整形变量中
}
}
int main()
{
test();
//test()函数中p为局部变量,出test()函数后局部变量p就会被销毁了
//此时再调用test()函数时就找不到p了
//想要释放p也已无法释放🙁,申请的内存未释放就会造成内存泄漏
while (1);//死循环
}
切记: 动态开辟的空间⼀定要释放,并且正确释放。
malloc/calloc/realloc申请的内存如果不想使用可以用free释放,如果没有使用free释放,当程序运行结束后,所申请的空间也会由操作系统回收的♻️
尽量做到:1.谁(可能是函数)申请的空间谁释放(malloc/calloc/realloc和free要成对出现);2.如果不能释放,要告诉使用者(可以告诉使用者其地址,相关文档信息等),记得将其释放
//注意👀:
//即使malloc与free成对出现也可能会造成内存泄漏
#include<stdio.h>
#include<stdlib.h>
void test()
{
int* p = (int*)malloc(100);
//使用
int n = 3;
if (n > 0)
return;//直接返回了,后面的free无法执行了,也会造成内存泄漏
free(p);
p = NULL;
}
int main()
{
test();
//
while (1);
}
4.动态内存经典笔试题分析
4.1 题目1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void GetMemory(char* p)//指针变量str中的空指针传给指针变量p
{
p = (char*)malloc(100);//malloc申请的100个字节的起始地址传给指针变量p
//形参变量p只能在GetMemory()函数内部使用
//函数一旦结束p就会被销毁,还给操作系统,p的空间也就不在了
//故函数结束后str中仍为NULL
}
void Test(void)
{
char* str = NULL;
GetMemory(str);//传值调用GetMemory()函数
strcpy(str, "hello world");//此处相当于对NULL进行解引用操作,会出现程序崩溃的现象
printf(str);//此处就不能打印str了
}
int main()
{
Test();
return 0;
}
//值传递中形参p是实参str的一份临时拷贝,p有自己的空间只是拿了str的内容
//将str的值放到p中不会影响str,若想修改str的话则最好将str的地址传给GetMemory()函数
//可将代码进行如下修改
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
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;
}
若不将str的地址传给GetMemory()函数,利用以下代码也可实现相关功能:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char* GetMemory()
{
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;
}
int main()
{
Test();
return 0;
}
4.2 题目2
//以上代码与以下代码本质原因相同
#include<stdio.h>
int* test()
{
int n = 10;
return &n;
//注意👀;
//局部变量n的值是可以返回的,相当于把n的值带回到调用函数处了
//但地址是不可以返回的,因为地址所指向的空间不在了
}
int main()
{
int* p = test();
printf("%d\n", *p);
return 0;
}
4.3 题目3
#include<stdio.h>
#include<string.h>
#include<stdlib.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);
}
int main()
{
Test();
return 0;
}
//以上代码唯一的问题就是没有进行free操作,若函数返回后,程序由于某种原因无法结束就会造成内存泄漏
//此代码程序结束后会自动free,但最好还是要自己free一下
//将其改写为以下代码后就完美了🤩
#include<stdio.h>
#include<string.h>
#include<stdlib.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(str);
str = NULL;
}
int main()
{
Test();
return 0;
}
4.4 题目4
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void Test(void)
{
char* str = (char*)malloc(100);
strcpy(str, "hello");
free(str);
if (str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
int main()
{
Test();
return 0;
}
5.柔性数组
C99中,结构体中的最后⼀个元素允许是未知大小的数组,就叫做柔性数组成员。
例如:
#include<stdio.h>
struct S
{
char c;
int n;
int arr[];//柔性数组
};
struct S
{
char c;
int n;
int arr[0];//[]中写0也意味着数组没有指定大小,但有些编译器可能会报错无法编译
//柔性数组
}
5.1 柔性数组的特点
• 结构中的柔性数组成员前面必须至少⼀个其他成员。
• sizeof返回的这种结构大小不包括柔性数组的内存。
• 包含柔性数组成员的结构用malloc()函数进行内存的动态分配,并且分配的内存应该大于结构体的大小,以适应柔性数组的预期大小。
#include<stdio.h>
#include<stdlib.h>
struct S
{
int n;
int arr[];
};
int main()
{
struct S* ps=(struct S*)malloc(sizeof(struct S) + 5 * sizeof(int));//假设希望柔性数组的大小为5个整型的大小
//malloc()函数返回的是所申请空间的地址,可用结构体指针变量接收返回值
return 0;
}
//代码1
#include<stdio.h>
#include<stdlib.h>
struct S
{
int n;
int arr[];
};
int main()
{
struct S* ps=(struct S*)malloc(sizeof(struct S) + 5 * sizeof(int));
if (ps == NULL)
{
perror("malloc");
return 1;
}
ps->n = 100;
//柔性数组的使用
int i = 0;
for (i = 0; i < 5; i++)
{
ps->arr[i] = i;
}
//调整空间
struct S* ptr=(struct S*)realloc(ps,sizeof(struct S)+10*sizeof(int));
if (ptr != NULL)
{
ps = ptr;
}
/*
使用
……
*/
//释放
free(ps);
ps = NULL;
return 0;
}
//代码2
#include<stdio.h>
#include<stdlib.h>
struct S
{
int n;
int* arr;
};
int main()
{
struct S* ps = (struct S*)malloc(sizeof(struct S));
if (ps == NULL)
{
perror("malloc");
return 1;
}
ps->arr = (int*)malloc(5 * sizeof(int));
if (ps->arr == NULL)
return 1;//直接返回
ps->n = 100;
//使用
int i = 0;
for (i = 0; i < 5; i++)
{
ps->arr[i]=i;
}
//调整数组大小
int* ptr = (int*)realloc(ps->arr, 10 * sizeof(int));
if (ptr != NULL)
{
ps->arr = ptr;
}
/*
使用
……
*/
//释放
free(ps->arr);//先释放ps->arr然后再释放ps,若先释放ps的话ps->arr就会找不到了🤦
free(ps);
return 0;
}
上述代码1和代码2可以完成同样的功能,但是方法1的实现有两个好处:
第⼀个好处是:方便内存释放,如果我们的代码是在⼀个给别人用的函数中,你在里面做了两次内存分配,并把整个结构体返回给用户。用户调用free可以释放结构体,但是用户并不知道这个结构体内的成员也需要free,所以不能指望用户来发现这个事。如果我们把结构体的内存以及其成员要的内存⼀次性分配好了,并返回给用户⼀个结构体指针,用户做⼀次free就可以把所有的内存释放了。
第⼆个好处是:这样有利于访问速度. 连续的内存有益于提高访问速度,也有益于减少内存碎片。(但实际上也没多高,避免不了要用做偏移量的加法来寻址)
6.C/C++中程序内存区域划分
C/C++程序内存分配的几个区域:
- 栈区(stack):在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束时 这些存储单元自动被释放。栈内存分配运算内置于处理器的指令集中,效率很高,但是分配的内存容量有限。栈区主要存放运行函数而分配的局部变量、函数参数、返回数据、返回地址等。
- 堆区(heap):⼀般由程序员分配释放,若程序员不释放,程序结束时可能由OS回收。分配方式类似于链表。
- 数据段(静态区):(static)存放全局变量、静态数据。程序结束后由系统释放。
- 代码段:存放函数体(类成员函数和全局函数
💓期待你的一键三连,你的鼓励是我创作的动力之源💓 |