• 【进阶C语言】动态内存分配


    本章大致内容介绍:

    1.malloc函数和free函数

    2.calloc函数

    3.realloc函数

    4.常见错误案例

    5.笔试题详解

    6.柔性数组

    一、malloc和free

    1.malloc函数

    (1)函数原型

    函数参数:根据用户的需求需要开辟多大的字节空间,为无符号的字节。

    返回值:malloc函数成功开辟内存后,会返回该内存的起始地址,可以根据需要强制转换成任意的类型;若开辟空间失败,则会返回空指针(NULL)。

    头文件:#include

    (2)使用方法

    1)申请空间:

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

    目的:申请十个整形空间,所以参数传:4*10=40。

    结果:用一个整形指针来接收其返回值

    2)检查安全和使用

    1. #include
    2. #include
    3. int main()
    4. {
    5. int* p = (int*)malloc(40);
    6. if (p == NULL)//必须对指针安全性检查
    7. {
    8. printf("申请空间失败\n");
    9. return;
    10. }
    11. //申请成功就开始用
    12. int i = 0;
    13. for (i=0;i<10;i++)
    14. {
    15. *(p+i) = i;
    16. }
    17. i = 0;
    18. for (i=0;i<10;i++)
    19. {
    20. printf("%d\n",*(p+i));
    21. }
    22. return 0;
    23. }

    当使用结束之后,我们需要删除该动态生成的空间,则需要对空间进行释放,这就是我们接下来讲的free。

    2.free函数

    (1)函数原型

    1.参数为动态开辟内存的首地址

    2.无参数返回

    3.头文件#include

    (2)配合动态内存开辟的函数使用

    前面malloc函数开辟的内存还没释放,接下来它们配合使用。

    1. #include
    2. #include
    3. int main()
    4. {
    5. int* p = (int*)malloc(40);
    6. if (p == NULL)
    7. {
    8. printf("申请空间失败\n");
    9. return;
    10. }
    11. //申请成功就开始用
    12. int i = 0;
    13. for (i=0;i<10;i++)
    14. {
    15. *(p+i) = i;
    16. }
    17. i = 0;
    18. for (i=0;i<10;i++)
    19. {
    20. printf("%d\n",*(p+i));
    21. }
    22. free(p);
    23. p = NULL;//及时将指针置空
    24. return 0;
    25. }

    注意事项:

    1.free只能释放由动态内存开辟的空间

    2.free释放的是指针所指向的那块空间,释放后指针仍在,但是指向的空间不咋了,就会变成野指针,所以我们需要及时置空。

    二、calloc

    1.函数定义

    函数参数:第一个参数是需要开辟的数据个数,第二个是该数据类型的内存大小。

    返回值:calloc函数成功开辟内存后,会返回该内存的起始地址,可以根据需要强制转换成任意的类型;若开辟空间失败,则会返回空指针(NULL)。

    头文件:#include

    2.calloc的使用

    目的:需要开辟10个整形空间

    1. #include
    2. #include
    3. int main()
    4. {
    5. int* p = (int*)calloc(10,sizeof(int));
    6. if (p == NULL)
    7. {
    8. printf("申请空间失败\n");
    9. return;
    10. }
    11. //申请成功就开始用
    12. int i = 0;
    13. for (i = 0; i < 10; i++)
    14. {
    15. *(p + i) = i;
    16. }
    17. i = 0;
    18. for (i = 0; i < 10; i++)
    19. {
    20. printf("%d\n", *(p + i));
    21. }
    22. free(p);
    23. p = NULL;//及时将指针置空
    24. return 0;
    25. }

    运行结果:

    根据malloc和calloc函数使用的两段代码,好像除了名字和参数之外,其他没什么不同呀?其实他们还有一处区别。

    3.calloc函数与malloc函数的区别

    (1)区别

    malloc函数开辟好空间之后,并不会对其初始化,但是calloc函数开辟好空间之后,会将数据的每一个字节都初始化成0。

    (2)对照

    1)malloc

    2)calloc

    除了以上三点不同之外,其他的都一样。所以我们需要根据内存需求,需不需要初始化内存而选择合适的开辟方式。

    三、realloc

    1.函数定义

    realloc可以对已有的内存进行调整

    函数参数:ptr是要调整的内存地址,size为内存调整之后的新大小,单位是内存总大小(字节)

    返回值:内存调整后的起始地址,同样有申请内存成功和失败两种情况

    头文件:#include

    2.realloc申请空间成功的两种情况

    (1)原空间后的空间足够大

    开辟空间方式:直接原有内存之后直接追加空间,原来空间的数据不发生变化。

    (2)原空间之后没有足够大的空间 

         原有空间之后没有足够多的空间时,扩展的方法是:在堆空间上另找一个合适大小
    的连续空间来使用。这样函数返回的是一个新的内存地址。而原有数据也会被拷贝到新内存中。

    3.realloc的使用

    1. #include
    2. #include
    3. int main()
    4. {
    5. int* p = (int*)calloc(10,sizeof(int));
    6. if (p == NULL)
    7. {
    8. printf("申请空间失败\n");
    9. return;
    10. }
    11. //申请成功就开始用
    12. int i = 0;
    13. for (i = 0; i < 10; i++)
    14. {
    15. *(p + i) = i;
    16. }
    17. i = 0;
    18. for (i = 0; i < 10; i++)
    19. {
    20. printf("%d\n", *(p + i));
    21. }
    22. //要求加大空间内存
    23. int* ptr = realloc(p,40*sizeof(int));
    24. if (ptr == NULL)
    25. {
    26. printf("内存开辟失败\n");
    27. return;
    28. }
    29. p = ptr;//将新开辟好的内存赋值原地址
    30. free(p);
    31. p = NULL;//及时将指针置空
    32. return 0;
    33. }

    realloc的使用一般在原有空间的情况下,同样也需要对指针进行判空操作和free。

    我们也可以看到,free和这些函数是紧紧联系在一起的。

    四、常见错误解析

    这些错误都是动态内存开辟前后的问题,与指针也有很大的联系

    1.对NULL指针的解引用操作

    错误写法:

    1. int main()
    2. {
    3. int* p = (int*)malloc(4);
    4. *p = 20;
    5. printf("%d\n",*p);
    6. return 0;
    7. }

    malloc有可能开辟动态内存失败,则会返回NULL,这个时候对NULL指针解引用操作就是非法的。

    正确写法:

    1. int main()
    2. {
    3. int* p = (int*)malloc(4);
    4. *p = 20;
    5. if (p == NULL)//对指针安全性限制
    6. {
    7. perror(malloc);
    8. return;
    9. }
    10. printf("%d\n",*p);
    11. //后续需要对内存释放
    12. return 0;
    13. }

     知识点1:在每次动态内存开辟完成之后,都要先对其指针进行判空操作;若非空,才能对其进行后续的操作。

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

    错误写法:

    1. int main()
    2. {
    3. int i = 0;
    4. int* p = (int*)malloc(10 * sizeof(int));
    5. if (NULL == p)
    6. {
    7. exit(EXIT_FAILURE);
    8. }
    9. for (i = 0; i <= 10; i++)
    10. {
    11. *(p + i) = i;//当i是10的时候越界访问
    12. }
    13. free(p);
    14. }

    错误的后果提示:

    知识点2:在对指针解引用操作时,要注意指针所指向的个数

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

    错误写法:

    1. test()
    2. {
    3. int a = 100;
    4. int* p = &a;
    5. free(p);//错误
    6. }

    知识点3:free函数只能释放动态开辟的内存,否则会非法。

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

    错误写法:

    1. int *p = (int *)malloc(100);
    2. p++;
    3. free(p);//p不再指向动态内存的起始位置

    当p++之后,p指向的起始位置就变了,当free(p)之后,会释放不完整,也会造成内存泄漏。

    知识点4:使用指针,尽量不要改变指针指向的起始地址。可以再重新使用新指针进行++或--操作;或者+1/-1操作。

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

    错误写法:

    1. void test()
    2. {
    3. int *p = (int *)malloc(100);
    4. free(p);
    5. free(p);//重复释放
    6. }

    知识点5:切记要对内存释放,但是每一块内存有且只能释放一次。

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

    错误:

    1. void test()
    2. {
    3. int *p = (int *)malloc(100);
    4. if(NULL != p)
    5. {
    6. *p = 20;
    7. }
    8. }
    9. int main()
    10. {
    11. test();
    12. while(1);
    13. }

    这是忘记对动态内存的释放的,也是不可取的。

    五、关于动态内存开辟的笔试题

    分析下面四道代码题存在什么问题

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

    1.对NULL解引用操作

    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. }

    1.str指针为空

    2.malloc开辟的空间只是被p指向,没有被str指向(相当于形参的改变不影响实参)

    3.所以strcpy函数就会对NULL指针进行解引用操作

    4.没有free操作,还会操作内存泄漏

    图解:

    正确写法:

    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. free(str);
    12. str=NULL;
    13. }

    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. }

    1.字符数组p为栈空间的局部变量,函数返回后会被销毁

    2.数组被销毁,返回的p就是野指针(所指向的空间已不属于自己)

     类型代码情况:

    1. int* test()
    2. {
    3. int a = 10;
    4. return &a;
    5. }
    6. int main()
    7. {
    8. int* p = test();
    9. printf("%d\n",*p);
    10. return 0;
    11. }

    这种运行的结果仍然可以得到10,虽然空间依然属于p,但是值仍在,没有被其他的数据覆盖。但是下面这种情况则不行。

    3.题目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. }

    动态开辟的内存,最后没有被free释放

    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. }

    1.str所指向的空间已被销毁

    2.str变成野指针,对其解引用操作为非法

    六、柔性数组

    1.柔性数组的定义

    标准定义:C99 中,结构中的最后一个元素允许是未知大小的数组,这就叫做『柔性数组』成员。

    也就是说,柔性数组不是指简单的数组,而是在结构体中的数组。

    有两种写法:

    第一种:

    1. typedef struct st_type
    2. {
    3. int i;
    4. int a[0];//柔性数组成员
    5. }type_a;

     a数组就称为柔性数组。但是这种定义方式容易报错,所以我们还有第二种。

    第二种:

    1. typedef struct st_type
    2. {
    3. int i;
    4. int a[];//柔性数组成员
    5. }type_a;

    就是不需要指定数组的大小,数组的大小是未知的。

    2.柔性数组的特点

    (1)sizeof 返回的这种结构大小不包括柔性数组的内存。

    (2)结构中的柔性数组成员前面必须至少一个其他成员。

    因为柔性数组是不计入sizeof的计算的,只有柔性数组成员sizeof就会出错。

    (3)包含柔性数组成员的结构用malloc ()函数进行内存的动态分配,并且分配的内存应该大于结构的大小,以适应柔性数组的预期大小。

    在计算包含柔性数组的结构体时,柔性数组是不计入内存的计算的。大于结构体内存大小的部分就会分配给柔性数组。

     (4)代码验证

    1. struct S
    2. {
    3. int a;
    4. int arr[];
    5. };
    6. int main()
    7. {
    8. struct S s;
    9. printf("%zd\n",sizeof(s));//计算该结构体的内存大小
    10. return 0;
    11. }

    运行的结果:

     柔性数组确实是不会参加sizeof对结构体的计算

    3.柔性数组的使用

    (1)开辟空间

    1. #include
    2. #include
    3. #include
    4. struct S
    5. {
    6. int a;
    7. int arr[];
    8. };
    9. int main()
    10. {
    11. struct S* ps=(struct S*)malloc(sizeof(struct S)+16);
    12. if (ps == NULL)
    13. {
    14. perror(malloc);
    15. return;
    16. }
    17. return 0;
    18. }

    (2)增容(realloc函数)

    1. #include
    2. #include
    3. #include
    4. struct S
    5. {
    6. int a;
    7. int arr[];
    8. };
    9. int main()
    10. {
    11. struct S* ps=(struct S*)malloc(sizeof(struct S)+16);
    12. if (ps == NULL)
    13. {
    14. perror(malloc);
    15. return;
    16. }
    17. struct S* str = (struct S*)realloc(ps,sizeof(struct S)+40);
    18. if (str != NULL)
    19. {
    20. ps = str;
    21. }
    22. else
    23. {
    24. perror(realloc);
    25. return;
    26. }
    27. return 0;
    28. }

     用malloc开辟空间之后,再用reallo增容(减容)。增容之后的空间都会加在柔性数组上,这个时候数组的大小就可以根据realloc变化,因此称为柔性数组。

     

    4.柔性数组的优势

    (1)方便内存释放

    1. #include
    2. #include
    3. #include
    4. struct S
    5. {
    6. int a;
    7. int arr[];//定义一个柔性数组
    8. };
    9. int main()
    10. {
    11. struct S* ps=(struct S*)malloc(sizeof(struct S)+16);
    12. if (ps == NULL)
    13. {
    14. perror(malloc);
    15. return;
    16. }
    17. struct S* str = (struct S*)realloc(ps,sizeof(struct S)+40);
    18. if (str != NULL)
    19. {
    20. ps = str;
    21. }
    22. else
    23. {
    24. perror(realloc);
    25. return;
    26. }
    27. free(ps);
    28. ps = NULL;
    29. return 0;
    30. }

    因为开辟的空间都是连续的,在一块内存中,所以只需要free一次即可。

    我们再对比一下另一种写法就更加明显了。

     结构体中有指针的写法:

    1. struct S
    2. {
    3. char c;
    4. int i;
    5. int* data;//定义一个指针
    6. };
    7. int main()
    8. {
    9. struct S* ps = (struct S*)malloc(sizeof(struct S));
    10. if (ps == NULL)
    11. {
    12. perror("malloc1");
    13. return 1;
    14. }
    15. ps->c = 'w';
    16. ps->i = 100;
    17. ps->data = (int*)malloc(20);
    18. if (ps->data == NULL)
    19. {
    20. perror("malloc2");
    21. return 1;
    22. }
    23. int i = 0;
    24. for (i = 0; i < 5; i++)
    25. {
    26. ps->data[i] = i;
    27. }
    28. for (i = 0; i < 5; i++)
    29. {
    30. printf("%d ", ps->data[i]);
    31. }
    32. //空间不够了,增容
    33. int* ptr = (int*)realloc(ps->data, 40);
    34. if (ptr == NULL)
    35. {
    36. perror("realloc");
    37. return 1;
    38. }
    39. else
    40. {
    41. ps->data = ptr;
    42. }
    43. //增容成功就使用
    44. //...
    45. //释放
    46. free(ps->data);//第一次
    47. ps->data = NULL;
    48. free(ps);//第二次
    49. ps = NULL;
    50. return 0;
    51. }

    1.两次开辟空间的原因是使得他们的数据都开辟在堆区上

    2.使得跟第一种一样的写法,突然第一种的优势

    3.这种写法开辟的空间是不连续的,容易造成空间零碎空间,导致空间浪费。

    (2)有利于访问速度和节约内存

    连续的内存有益于提高访问速度,也有益于减少内存碎片,更大程度的利用内存空间。

  • 相关阅读:
    112.HBase Endpoint类型的Coprocessor开发与部署
    跳跃游戏 I - VII
    UML统一建模语言
    Spring Boot技术知识点:如何解读@Validated注解
    【宋红康 MySQL数据库 】【高级篇】【13】索引优化与查询优化
    Linux中通过什么命令可以过滤控制字符?
    计算机毕设(附源码)JAVA-SSM基于的装修公司运营管理管理系统
    Linux命令笔记三
    YOLOv5结合华为诺亚VanillaNet Block模块
    甲基咪唑离子液体[MIM]Cl修饰Fe3O4@SiO2磁性纳米颗粒(Fe3O4@SiO2@[MIM]Cl)采用硅烷化法制备
  • 原文地址:https://blog.csdn.net/2301_77053417/article/details/133276312