目录
不管是C还是C++中都会有大量的使用,使用C/C++实现数据结构的时候,也会使用动态内存管理
1.为什么要有动态内存分配
#include <stdio.h>
int n = 10;
char arr[20];//20个字节
int arr2[20];//80个字节
//上面的内存申请方式,一旦申请好空间,大小就无法调整
上述开辟空间的方式有两个特点:
- 空间开辟大小是固定的
- 数组在声明的时候,必须指定数组的长度,数组空间一旦确定了大小就不能调整
但是对于空间的需求,不仅仅是上述的情况,有时候我们需要的空间大小在程序运行的时候才能知道,那数组的编译时开辟空间的方式就不能满足了
C语言引入了动态内存开辟,让程序员自己可以申请和释放空间,比较灵活
2.malloc和free
2.1 malloc
头文件:stdlib.h
C语言提供了一个动态内存开辟的函数:
void* malloc(size_t size);
这个函数向内存申请一块连续可用的空间,并返回指向这块空间的指针
- 如果开辟成功,则返回一个指向开辟好空间的指针
- 如果开辟失败,则返回一个NULL指针,因此malloc的返回值一定要做检查
- 返回值的类型是void*,所以malloc函数并不知道开辟空间的类型,具体在使用的时候使用者自己来决定
- 如果参数size为0,malloc的行为是标准未定义的,取决于编译器
2.2 free
头文件:stdlib.h
C语言提供了另外一个函数free,专门是用来做动态内存的释放和回收的,函数原型如下:
void free(void* ptr);//释放空间的起始地址
free函数用来释放动态开辟的内存
- 如果参数ptr指向的空间不是动态开辟的,那free函数的行为是未定义的
- 如果参数ptr是NULL指针,则函数什么事都不用做
举个栗子:
#include <stdio.h>
#include <stdlib.h>
int main()
{
//20个字节
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;
}//释放内存
//void free(void* ptr);
free(p);//传递给free函数的要是释放的内存空间的起始地址
p = NULL;//避免成为野指针
return 0;
}
3. calloc和realloc
3.1 calloc
C语言还提供了一个函数叫calloc,calloc函数也用来动态内存分配,原型如下:
void* calloc(size_t num, size_t size);
- 函数的功能是为num个大小为size的元素开辟一块空间,并且把空间的每个字节初始化为0
- 与函数malloc的区别只在于calloc会在返回地址之前把申请的空间的每个字节初始化为0
举个栗子:
#include <stdio.h>
#include <stdlib.h>
//void* calloc(size_t num, size_t size);
int main()
{
int* p = (int*)calloc(5, sizeof(int));
if (p == NULL)
{
perror("calloc");
return 1;
}
int i = 0;
for (i = 0; i < 5; i++)
{
printf("%d ", *(p + i));//0 0 0 0 0 ——初始化为0
}
free(p);
p = NULL;
return 0;
}
如果我们对申请的内存空间的内容要求初始化,那么可以很方便地使用calloc函数来完成任务
3.2 realloc
-
realloc函数的出现让动态内存管理更加灵活
-
有时候我们会发现过去申请的空间太小了,有时我们又会觉得申请的空间过大了,那为了合理地使用内存,我们一定会对内存的大小做灵活地调整,那realloc函数就可以做到对动态开辟内存大小的调整
void* realloc(void* ptr, size_t size);
- ptr是要调整的内存地址
- size调整之后新大小
- 返回值为调整之后的内存起始位置
- 这个函数调整原内存空间大小的基础上,还会将原来内存中的数据移动到新的空间
- realloc在调整内存空间的是存在两种情况:
- 原有空间之后有足够大的空间
- 原有空间之后没有足够大的空间
如果后面的空间不够,将在堆区的内存中找一个新的空间,并且新的大小要求;
会将原来的数据拷贝到一份到新的空间
释放旧的空间,返回新的内存空间的起始地址
如果调整失败,返回NULL
#include <stdio.h>
#include <stdlib.h>
//void* realloc(void* ptr, size_t size);
int main()
{
int* p = (int*)malloc(5 * sizeof(int));
if (p == NULL)
{
perror("malloc");
return 1;
}
//使用
int i = 0;
for (i = 0; i < 5; i++)
{
*(p + i) = i + 1;
}
//希望将空间调整为40个字节
int* ptr = (int*)realloc(p, 40);
/*如果后面的空间不够,将在堆区的内存中找一个新的空间,并且新的大小要求;
会将原来的数据拷贝到一份到新的空间
释放旧的空间,返回新的内存空间的起始地址
如果调整失败,返回NULL*/
if (ptr != NULL)
{
p = ptr;
for (i = 5; i < 10; i++)
{
*(p + i) = i + 1;
}
for (i = 0; i < 10; i++)
{
printf("%d ", *(p + i));//1 2 3 4 5 6 7 8 9 10
}
free(p);
p = NULL;
}
else
{
perror("realloc");//调整失败
free(p);
p = NULL;
}
//使用40个空间
return 0;
}
realloc函数可以完成和malloc一样的功能
#include <stdio.h>
#include <stdlib.h>
int main()
{
realloc(NULL, 20);//==malloc(20);
}
4.常见的动态内存的错误
4.1对NULL指针的解引用操作
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main()
{
int* p = (int*)malloc(INT_MAX);
*p = 20;//如果p的值是NULL,就会有问题
//因此需要判断
if (p == NULL)
{
perror("malloc");
return 1;
}
//也可以用assert断言
assert(p);
return 0;
}
4.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;
}
4.3对非动态开辟内存使用free释放
#include <stdio.h>
int main()
{
int a = 10;//非动态开辟内存
int* p = &a;
free(p);
return 0;
}
4.4使用free释放一块动态开辟内存的一部分
#include <stdio.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不再是动态申请内存的起始位置
p = NULL;
return 0;
}
4.5对同一块内存多次释放
#include <stdio.h>
#include <stdlib.h>
void test()
{
int* p = (int*)malloc(100);
free(p);
p = NULL;//如果没有这一句,将会出现错误
free(p);//重复释放
}
int main()
{
test();
return 0;
}
4.6动态开辟内存忘记释放(内存泄漏)
#include <stdio.h>
#include <stdlib.h>
void test()
{
int* p = (int*)malloc(100);
if (NULL != p)
{
*p = 20;
}
}
//找不到了,局部变量
//申请了内存空间,却没办法还
//内存泄漏
int main()
{
test();//
while(1);
}
malloc/calloc/realloc申请的内存,如果不想使用可以使用free释放
如果没有使用free来释放,当程序运行结束的时候,会由操作系统回收
5.动态内存经典笔试题分析
5.1 题目一
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void GetMemory(char* p)
{
p = (char*)malloc(100);//没有free——一直存在
}
void Test(void)
{
char* str = NULL;
GetMemory(str);//内存释放
strcpy(str, "Hello World");//str为NULL——非法访问(对空指针的解引用操作——程序崩溃)
printf(str);
}
int main()
{
Test();
return 0;
}
//1.内存泄漏
//2.程序崩溃
修改后:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void GetMemory(char** p)
{
*p = (char*)malloc(100);
}
void Test(void)
{
char* str = NULL;
GetMemory(&str);
strcpy(str, "Hello World");
printf(str);//Hello World
free(str);
str = NULL;
}
int main()
{
Test();
return 0;
}
另一种修改:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* GetMemory()
{
char* p = (char*)malloc(100);
return p;
}
void Test(void)
{
char* str = NULL;
str = GetMemory();
strcpy(str, "Hello World");
printf(str);//Hello World
free(str);
str = NULL;
}
int main()
{
Test();
return 0;
}
5.2 题目二
#include <stdio.h>
char* GetMemory(void)
{
char p[] = "hello world";
return p;//数组首元素地址
}
//出栈销毁
void Test(void)
{
char* str = NULL;
str = GetMemory();//野指针——所指空间已释放
//等GetMemory函数返回后,使用str指针去访问p数组,就是非法访问
//因为p数组的内存已经还给了操作系统
printf(str);
}
int main()
{
Test();
return 0;
}
5.3 题目三
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void GetMemory(char** p, int num)
{
*p = (char*)malloc(num);//没有free
}
void Test(void)
{
char* str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
int main()
{
Test();
return 0;
}
5.4 题目四
#define _CRT_SECURE_NO_WARNINGS
#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);//world
}
}
int main()
{
Test();
return 0;
}
6.柔性数组
C99中,结构中的最后一个元素允许是未知大小的数组,这就叫做柔性数组成员
例如:
#include <stdio.h>
struct st_type
{
char c;
int n;
int arr[];//柔性数组
//或者:int arr[0];
};
6.1柔性数组的特点
- 结构中的柔性数组成员前面必须至少有一个其他成员(为了计算大小)
- sizeof返回的这种结构大小不包括柔性数组的内存
- 包含柔性数组成员的结构用malloc()函数进行内存的动态分配,并且分配的内存应该大于结构的大小,以适应柔性数组的预期大小
6.2柔性数组的使用
#include <stdio.h>
#include <stdlib.h>
struct S
{
char c;
int n;
int arr[];//柔性数组
//或者:int arr[0];
};
int main()
{
//printf("%zd", sizeof(struct S));//8
struct S* ps = (struct S*)malloc(sizeof(struct S) + 5 * sizeof(int));//大小柔性变化
if (ps == NULL)
{
perror("malloc");
return 1;
}
ps->n = 100;
ps->c = 'A';
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;
}
//使数组可长可短的另一种方法:
struct S
{
int n;
int* arr;
};
int main()
{
struct S* ps = (struct S*)malloc(sizeof(struct S));
if (ps == NULL)
{
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);
free(ps);
return 0;
}
很明显,使用柔性数组更方便
6.3柔性数组的优势
方便内存释放:
如果我们的代码是在一个给别人用的函数中,你在里面做了二次内存分配,并把整个结构体返回给用户。用户调用free可以释放结构体,但是用户并不知道这个结构体内的成员也需要free,所以你不能指望用户来发现这个事,所以,如果我们把结构体的内存以及其成员要的内存一次性分配好了,并返回给用户一个结构体指针,用户做一次free就可以把所有的内存也给释放掉
有利于访问速度:
连续的内存有益于提高访问速度,也有益于减少内存碎片
C语言结构体里的成员数组和指针 | 酷 壳 - CoolShell
7.总结C/C++中程序内存区域划分
C/C++程序内存分配的几个区域:
- 栈区(stack):在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束时这些存储单元自动被释放。栈内存分配运算内置于处理器的指令集中,效率很高,但是分配的内存容量有限。栈区主要存放运行函数而分配的局部变量、函数参数、返回数据、返回地址等
- 堆区(heap):一般由程序员分配释放,若程序员不释放,程序结束时可能由OS回收。分配方式类似于链表
- 数据段(静态区):(static)存放全局变量、静态数据。程序结束后由系统释放
- 代码段:存放函数体(类成员函数和全局变量)的二进制代码