0


C语言进阶——动态内存管理

作者:敲代码の流川枫

博客主页:流川枫的博客

专栏:C语言从入门到进阶

语录:Stay hungry stay foolish

工欲善其事必先利其器,给大家介绍一款超牛的斩获大厂offer利器——牛客网

点击免费注册和我一起刷题吧

1. 为什么存在动态内存

我们经常用到的开辟内存方式有:

  1. int a = 40;
  2. int arr[40] = {0};

上述开辟内存方式的特点:

1.开辟空间的大小是固定的

2.数组在申明的时候,必须指定数组的长度,它所需要的内存在编译时分配

有时候我们需要的空间大小是在程序运行时才能知道,上述方式满足不了要求,所以出现了动态内存的开辟

2. 分配动态内存函数的介绍

2.1 malloc

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

  1. void* malloc (size_t size);

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

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

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

返回值的类型是void*,所以malloc函数并不知道开辟空间的类型,具体在使用的时候使用者自己来决定

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

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<string.h>
  5. #include<errno.h>
  6. int main()
  7. {
  8. int arr[10] = { 0 };
  9. //动态内存开辟
  10. int* p = (int*)malloc(40);
  11. if (p == NULL)
  12. {
  13. printf("%s\n", strerror(errno));
  14. return 1;
  15. }
  16. //使用
  17. int i = 0;
  18. for (i=0;i<10;i++)
  19. {
  20. *(p + i) = i;
  21. }
  22. for (i = 0; i < 10; i++)
  23. {
  24. printf("%d ", *(p + i));
  25. }
  26. printf("\n");
  27. return 0;
  28. }

这里没有free,当程序退出的时候, 系统会回收该空间

2.2 free

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

  1. void free (void* ptr);

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

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

如果参数ptr是NULL指针,则函数什么事都不做

malloc和free都声明在stdlib.h头文件中

  1. int main()
  2. {
  3. int arr[10] = { 0 };
  4. //动态内存开辟
  5. int* p = (int*)malloc(40);
  6. if (p == NULL)
  7. {
  8. printf("%s\n", strerror(errno));
  9. return 1;
  10. }
  11. //使用
  12. int i = 0;
  13. for (i=0;i<10;i++)
  14. {
  15. *(p + i) = i;
  16. }
  17. for (i = 0; i < 10; i++)
  18. {
  19. printf("%d", *(p + i));
  20. }
  21. //释放
  22. free(p);
  23. p = NULL;
  24. return 0;
  25. }

不用free函数释放空间会出现内存泄漏,free回收完系统空间时,p还是指向那块吧被释放的空间,为了避免出现野指针的问题,一定要将它置为空指针

2.3 calloc

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

  1. void* calloc (size_t num, size_t size);

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

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

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<string.h>
  5. #include<errno.h>
  6. int main()
  7. {
  8. int arr[10] = { 0 };
  9. //动态内存开辟
  10. int* p = (int*)calloc(10,sizeof(int));
  11. if (p == NULL)
  12. {
  13. printf("%s\n", strerror(errno));
  14. return 1;
  15. }
  16. //使用
  17. /*int i = 0;
  18. for (i=0;i<10;i++)
  19. {
  20. *(p + i) = i;
  21. }*/
  22. int i = 0;
  23. for (i = 0; i < 10; i++)
  24. {
  25. printf("%d ", *(p + i));
  26. }
  27. printf("\n");
  28. free(p);
  29. p = NULL;
  30. return 0;
  31. }

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

2.4 realloc

realloc函数的出现让动态内存管理更加灵活

有时会我们发现过去申请的空间太小了,有时候我们又会觉得申请的空间过大了,那为了合理的时候内存,我们一定会对内存的大小做灵活的调整。那realloc函数就可以做到对动态开辟内存大小的调整。函数原型如下:

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

ptr是要调整的内存地址

size调整之后新大小

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

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

realloc在调整内存空间的是存在两种情况:

情况1:

当是情况1 的时候,原有空间之后没有足够多的空间时,扩展的方法是:在堆空间上另找一个合适大小的连续空间来使用。这样函数返回的是一个新的内存地址,旧的地址和数据都会被自动释放

情况2:

当是情况2 的时候,要扩展内存就直接原有内存之后直接追加空间,原来空间的数据不发生变化

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<string.h>
  5. #include<errno.h>
  6. int main()
  7. {
  8. int arr[10] = { 0 };
  9. //动态内存开辟
  10. int* p = (int*)malloc(40);
  11. if (p == NULL)
  12. {
  13. printf("%s\n", strerror(errno));
  14. return 1;
  15. }
  16. //使用
  17. int i = 0;
  18. for (i=0;i<10;i++)
  19. {
  20. *(p + i) = i+1;
  21. }
  22. //扩容
  23. //追加40个字节
  24. int *ptr = (int* )realloc(p, 80);
  25. if (ptr != NULL)
  26. {
  27. p = ptr;
  28. }
  29. //使用
  30. for (i = 0; i < 10; i++)
  31. {
  32. printf("%d ", *(p + i));
  33. }
  34. printf("\n");
  35. free(p);
  36. p = NULL;
  37. return 0;
  38. }

**注意:开辟多了会出现内存碎片,导致内存利用率下降,程序的效率也会下降 **

3. 常见的动态内存错误

3.1 对NULL指针的解引用操作

  1. int main()
  2. {
  3. int* p = (int*)malloc(40);
  4. if (p == NULL)
  5. {
  6. return 1;
  7. }
  8. *p = 20;
  9. free(p);
  10. p = NULL;
  11. return 0;
  12. }

要判断是否为空指针,如果是空指针就是开辟内存失败,出现对空指针的解引用

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

  1. int main()
  2. {
  3. int* p = (int*)malloc(40);
  4. if (p == NULL)
  5. {
  6. printf("%s", strerror(errno));
  7. }
  8. int i = 0;
  9. for (i = 0; i <= 10; i++)
  10. {
  11. p[i] = i;
  12. }
  13. free(p);
  14. p = NULL;
  15. return 0;
  16. }

当i是10的时候越界访问

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

  1. void test()
  2. {
  3. int a = 10;
  4. int* p = &a;
  5. free(p);
  6. p = NULL;
  7. }
  8. int main()
  9. {
  10. test();
  11. return 0;
  12. }

free函数只能对在堆上开辟的动态内存进行释放

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

  1. int main()
  2. {
  3. int* p = (int*)malloc(40);
  4. if (p == NULL)
  5. {
  6. printf("%s", strerror(errno));
  7. }
  8. int i = 0;
  9. for (i = 0; i <= 10; i++)
  10. {
  11. *p = i;
  12. p++;
  13. }
  14. //释放
  15. free(p);
  16. p = NULL;
  17. return 0;
  18. }

程序运行起来,p已经不指向最开始的地址,因此最后释放,也不会将动态开辟的内存全部释放

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

  1. int main()
  2. {
  3. int* p = (int*)malloc(40);
  4. free(p);
  5. //.....
  6. free(p);
  7. return 0;
  8. }

重复释放并且没有将p置为空指针,会报错

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

  1. void test()
  2. {
  3. int* p = (int*)malloc(40);
  4. //....
  5. int a = 0;
  6. scanf("%d", &a);
  7. //...
  8. if (a == 10)
  9. return;
  10. free(p);
  11. p == NULL;
  12. }
  13. int main()
  14. {
  15. test();
  16. return 0;
  17. }

当满足a==10,free是没有机会被执行的,并且函数结束就找不到该空间的地址了,也不会释放,内存出现泄漏

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

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

4. 几个经典的笔试题

运行Test 函数会有什么样的结果

笔试题1

  1. void GetMemory(char* p)
  2. {
  3. p= (char*)malloc(100);
  4. }
  5. void Test(void)
  6. {
  7. char* str = NULL;
  8. GetMemory(str);
  9. strcpy(str, "hello world");
  10. printf(str);
  11. }

解析:

笔试题2

  1. char* GetMemory(void)
  2. {
  3. char p[] = "hello world";
  4. return p;
  5. }
  6. void Test(void)
  7. {
  8. char*str = NULL;
  9. str = GetMemory();
  10. printf(str);
  11. }

解析:

笔试题3

  1. void GetMemory(char** p, int num)
  2. {
  3. *p= (char*)malloc(num);
  4. }
  5. void Test(void)
  6. {
  7. char* str = NULL;
  8. GetMemory(&str, 100);
  9. strcpy(str, "hello");
  10. printf(str);
  11. }

分析:

笔试题4

  1. void Test(void)
  2. {
  3. char* str = (char*) malloc(100);
  4. strcpy(str, "hello");
  5. free(str);
  6. if(str != NULL)
  7. {
  8. strcpy(str,"world");
  9. printf(str);
  10. }
  11. }

分析:

5. C/C++程序的内存开辟

6. 动态通讯录

动态通讯录:默认存放三个人的信息,不够则扩容,每次增加两个人的空间,在静态通讯录的基础上修改即可

参看静态通讯录

  1. #pragma once
  2. #include<stdio.h>
  3. #include<string.h>
  4. #include<assert.h>
  5. #include<stdlib.h>
  6. #define MAX 100
  7. #define MAX_NAME 20
  8. #define MAX_SEX 10
  9. #define MAX_TELE 12
  10. #define MAX_ADDR 30
  11. #define DEFAULT_Sz 3
  12. #define INC_SZ 2
  13. //类型的声明
  14. //
  15. //只是一个人的信息
  16. typedef struct PeoInfo
  17. {
  18. char name[MAX_NAME];
  19. int age;
  20. char sex[MAX_SEX];
  21. char tele[MAX_TELE];
  22. char addr[MAX_ADDR];
  23. }PeoInfo;
  24. //静态版本
  25. 通讯录(多个人的信息)
  26. //typedef struct Contact
  27. //{
  28. // PeoInfo data[100];//存放人的信息
  29. // int count;//记录当前通讯录有多少人的信息
  30. //}Contact;
  31. //
  32. //
  33. //动态版本
  34. typedef struct Contact
  35. {
  36. PeoInfo* data;//存放人的信息
  37. int count;//记录当前通讯录有多少人的信息
  38. int capacity;//记录当前通讯录容量
  39. }Contact;
  40. //初始化通讯录函数
  41. int InitContact(Contact *pc);
  42. //增加联系人到通讯录
  43. void addContact(Contact* pc);
  44. //打印通讯录信息
  45. void showContact(const Contact* pc);
  46. //删除指定联系人
  47. void delContact(Contact* pc);
  48. //查找指定联系人
  49. void SearchContact(Contact* pc);
  50. //修改指定联系人
  51. void modifyContact(Contact* pc);
  52. //按照名字排序通讯录内容
  53. void sortContact(Contact* pc);
  54. //销毁通讯录
  55. void DestroyContact(Contact* pc);
  56. //动态版本
  57. int InitContact(Contact* pc)
  58. {
  59. pc->count = 0;
  60. pc->data = (PeoInfo*)calloc(DEFAULT_Sz,sizeof(PeoInfo));
  61. if (pc->data == NULL)
  62. {
  63. printf("InitContact:%s\n", strerror(errno));
  64. return 1;
  65. }
  66. pc->capacity = DEFAULT_Sz;
  67. return 0;
  68. }

实现增容功能:

  1. //增容函数
  2. void CheckCapacity(Contact* pc)
  3. {
  4. if (pc->count == pc->capacity)
  5. {
  6. PeoInfo* ptr = (PeoInfo*)realloc(pc->data, (pc->capacity + INC_SZ) * sizeof(PeoInfo));
  7. if (ptr == NULL)
  8. {
  9. printf("addContact:%s\n", strerror(errno));
  10. }
  11. else
  12. {
  13. pc->data = ptr;
  14. pc->capacity += INC_SZ;
  15. printf("增容成功\n");
  16. }
  17. }
  18. }
  19. //动态版本
  20. void addContact(Contact* pc)
  21. {
  22. assert(pc);
  23. //增容
  24. CheckCapacity(pc);
  25. //添加信息
  26. printf("\n请输入名字:>");
  27. //每次放进去的信息都是放进data 下标为count的数组
  28. scanf("%s", pc->data[pc->count].name);
  29. printf("\n请输入年龄:>");
  30. //因为name是存放在数组中,数组名本身就是地址,不需要再取地址
  31. //这里的年龄是int 型变量,需要取地址
  32. scanf("%d", &(pc->data[pc->count].age));
  33. printf("\n请输入性别:>");
  34. scanf("%s", pc->data[pc->count].sex);
  35. printf("\n请输入电话:>");
  36. scanf("%s", pc->data[pc->count].tele);
  37. printf("\n请输入地址:>");
  38. scanf("%s", pc->data[pc->count].addr);
  39. pc->count++;
  40. printf("\n增加成功\n");
  41. }

free增容所开辟的空间:

  1. //销毁通讯录
  2. void DestroyContact(Contact* pc)
  3. {
  4. assert(pc);
  5. free(pc->data);
  6. pc->data = NULL;
  7. }

** “ 本期的分享就到这里了, 记得给博主一个三连哈,你的支持是我创作的最大动力!”**


本文转载自: https://blog.csdn.net/chenchenchencl/article/details/125887806
版权归原作者 敲代码の流川枫 所有, 如有侵权,请联系我们删除。

“C语言进阶&mdash;&mdash;动态内存管理”的评论:

还没有评论