动态内存管理(下)——“C”

简介: 动态内存管理(下)——“C”

各位CSDN的uu们你们好呀,小雅兰很久没有和大家见面啦,可不,我这不是就来了嘛,今天,小雅兰的内容仍然是动态内存管理的知识,今天主要是来看一些经典的题目,下面,就让我们进入动态内存管理的世界吧


几个经典的笔试题


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


柔性数组


几个经典的笔试题


题目 1 :

#define _CRT_SECURE_NO_WARNINGS 1
#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);
}
int main()
{
  Test();
  return 0;
}

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

acc5f9e4287c4dcf839a4c86051e5b3a.png

会观察到什么结果也没有,那么这段代码究竟存在什么问题呢?

388244f69b614267b7fa2ce31463e7d8.png

调用GetMemory函数的时候,str的传参为值传递,p是str的一份临时拷贝,所以在GetMemory函数内部讲动态开辟的空间的地址是存放在p的时候,不会影响str,所以GetMemort函数返回之后,str中依旧是NULL指针,strcpy函数就会调用失败,原因是对NULL的解引用操作,程序会崩溃

GetMemory函数内部malloc申请的空间没有机会释放,造成了内存泄漏

改正方法一:

#define _CRT_SECURE_NO_WARNINGS 1
#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);
  free(str);
  str = NULL;
}
int main()
{
  Test();
  return 0;
}

5530cf60916d4b1e9d961876904d8988.png

改正方法二:

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* GetMemory(char* p)
{
  p = (char*)malloc(100);
  return p;
}
void Test(void)
{
  char* str = NULL;
  GetMemory(str);
  strcpy(str, "hello world");
  printf(str);
  free(str);
  str = NULL;
}
int main()
{
  Test();
  return 0;
}

 题目 2 :

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* GetMemory(void)
{
  char p[] = "hello world";
  return p;
}
void Test(void)
{
  char* str = NULL ;
  str = GetMemory();
  printf(str);
}
int main()
{
  Test();
  return 0;
}

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

8b125ee349734fd39611e65851f9b5a4.png

为什么会出现这样的结果呢?


GetMemory函数内部创建的数组是临时的,虽然返回了数组的起始地址给了str,但是数组的内存出了GetMemory函数就被操作系统回收了,而str依然保存了数组的起始地址,这时如果使用str,str就是野指针


题目 3 :

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.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);
}
int main()
{
  Test();
  return 0;
}

如果仔细观察,就会发现:这段代码与我们在题目一中修改的代码十分相似,但是这段代码没有free操作,是咯,这段代码的问题就是这个啦,没有free操作,会造成内存泄漏

 

改进:

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.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(str);
  str = NULL;
}
int main()
{
  Test();
  return 0;
}

题目 4 :

#define _CRT_SECURE_NO_WARNINGS 1
#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;
}

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

cc77a29e989449958d706155646ab6fc.png

虽然这段代码确实打印出了结果,但是实际上,它还是有问题的

在这段代码中,执行到free(str);这行代码的时候,str指向的空间已经回收了,所以后面的if语句中的strcpy函数,一旦执行就是非法访问


C/C++程序的内存开辟9bb1b6bc9e7c472598ae577f892f81cc.png

C/C++程序内存分配的几个区域:


栈区(stack):在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束时这些存储单元自动被释放。栈内存分配运算内置于处理器的指令集中,效率很高,但是分配的内存容量有限。 栈区主要存放运行函数而分配的局部变量、函数参数、返回数据、返回地址等。

堆区(heap):一般由程序员分配释放, 若程序员不释放,程序结束时可能由OS回收 。分配方式类似于链表。

数据段(静态区)(static)存放全局变量、静态数据。程序结束后由系统释放。

代码段:存放函数体(类成员函数和全局函数)的二进制代码。

实际上普通的局部变量是在栈区分配空间的,栈区的特点是在上面创建的变量出了作用域就销毁。

但是被static修饰的变量存放在数据段(静态区),数据段的特点是在上面创建的变量,直到程序结束才销毁,所以生命周期变长。

fc45687768794361b740b6a213d6b243.png

柔性数组

也许你从来没有听说过柔性数组(flexible array)这个概念,但是它确实是存在的。

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

例如:

typedef struct st_type
{
  int i;
  int a[0];//柔性数组成员
}type_a;

有些编译器会报错无法编译可以改成:

typedef struct st_type
{
  int i;
  int a[];//柔性数组成员
}type_a;

柔性数组的特点:

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

struct SA
{
  int arr[0];//柔性数组成员
};

这样写是绝对不可以的!!!

struct SA
{
  int arr[];//柔性数组成员
};

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

#include<stdio.h>
struct S
{
  int n;
  char c;
  int arr[0];//柔性数组成员
};
int main()
{
  printf("%d ", sizeof(struct S));
  return 0;
}

6d1c8db0beab40879847722baca34e2b.png

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

bb1964066d224867b8c5f075fa0f9116.png

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
struct S
{
  int n;
  char c;
  int arr[0];//柔性数组成员
};
int main()
{
  struct S* ps = (struct S*)malloc(sizeof(struct S) + 10 * sizeof(int));
  if (ps == NULL)
  {
    printf("%s\n", strerror(errno));
    return 1;
  }
  //使用
  ps->n = 520;
  ps->c = 'y';
  int i = 0;
  for (i = 0; i < 10; i++)
  {
    ps->arr[i] = i;
  }
  for (i = 0; i < 10; i++)
  {
    printf("%d ", ps->arr[i]);
  }
  //释放
  free(ps);
  ps = NULL;
  return 0;
}

d929291db01d4297adc5d833678e5e49.png

柔性数组的使用

柔性数组方案——方案1:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
struct S
{
  int n;
  char c;
  int arr[0];//柔性数组成员
};
int main()
{
  struct S* ps = (struct S*)malloc(sizeof(struct S) + 10 * sizeof(int));
  if (ps == NULL)
  {
    printf("%s\n", strerror(errno));
    return 1;
  }
  //使用
  ps->n = 520;
  ps->c = 'y';
  int i = 0;
  for (i = 0; i < 10; i++)
  {
    ps->arr[i] = i;
  }
  for (i = 0; i < 10; i++)
  {
    printf("%d ", ps->arr[i]);
  }
  //调整arr数组的大小
  //柔性数组中柔性的体现
  //大小可变
  struct S* ptr = (struct S*)realloc(ps, sizeof(struct S) + 20 * sizeof(int));
  if (ptr == NULL)
  {
    printf("%s\n", strerror(errno));
    return 1;
  }
  //释放
  free(ps);
  ps = NULL;
  return 0;
}

f03ca1a2ddc349a5a59684979cbe055b.png

柔性数组的优势

a9e9d8ede5e74860af20745242dd8656.png

结构体中使用指针——方案2

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
struct S
{
  int a;
  char c;
  int* arr;
};
int main()
{
  struct S* ps = (struct S*)malloc(sizeof(struct S));
  if (ps == NULL)
  {
    perror("malloc1:");
    return 1;
  }
  int* ptr = (int*)malloc(10 * sizeof(int));
  if (ptr == NULL)
  {
    perror("malloc2:");
    return 1;
  }
  else
  {
    ps->arr = ptr;
  }
  //使用
  ps->a = 520;
  ps->c = 's';
  int i = 0;
  for (i = 0; i < 10; i++)
  {
    ps->arr[i] = i;
  }
  //打印
  for (i = 0; i < 10; i++)
  {
    printf("%d ", ps->arr[i]);
  }
  //扩容-调整arr的大小
  ptr = realloc(ps->arr, sizeof(int));
  if (ptr == NULL)
  {
    perror("realloc:");
    return 1;
  }
  else
  {
    ps->arr = ptr;
  }
  //使用
  //释放
  free(ptr);
  ptr = NULL;
  free(ps);
  ps = NULL;
  return 0;
}

上述这段代码其实也是能够实现柔性数组的功能的!!!

746259e99f9843e09b7766445c5d1d7a.png

918346794844405594fb54c21a032593.png

typedef struct st_type
{
  int i;
  int a[0];//柔性数组成员
}type_a;
//代码1
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);

 这样柔性数组成员a,相当于获得了100个整型元素的连续空间。

//代码2
typedef struct st_type
{
  int i;
  int* p_a;
}type_a;
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;

上述代码1和代码2可以完成同样的功能,但是 方法1 的实现有两个好处:


第一个好处是:方便内存释放


如果我们的代码是在一个给别人用的函数中,你在里面做了二次内存分配,并把整个结构体返回给用户。用户调用free可以释放结构体,但是用户并不知道这个结构体内的成员也需要free,所以你不能指望用户来发现这个事。所以,如果我们把结构体的内存以及其成员要的内存一次性分配好了,并返回给用户一个结构体指针,用户做一次free就可以把所有的内存也给释放掉。


第二个好处是:这样有利于访问速度


连续的内存有益于提高访问速度,也有益于减少内存碎片。(其实,我个人觉得也没多高了,反正你跑不了要用做偏移量的加法来寻址)


好啦,小雅兰今天的内容就到这里啦,还要继续加油噢,最近有点摆烂了,哈哈哈!!!

f844355d21c64f47b56de9ada9aae981.jpg

相关文章
|
6天前
|
程序员 编译器 C语言
动态内存管理
动态内存管理
|
19天前
|
编译器 程序员 C语言
动态内存管理(超详细!)
动态内存管理(超详细!)
27 2
|
7月前
|
C语言 Python
动态内存管理(下)
动态内存管理(下)
32 0
|
19天前
|
程序员 C语言 C++
详解动态内存管理!
详解动态内存管理!
|
19天前
|
安全 C++ 开发者
c++动态内存管理(二)
c++动态内存管理(二)
92 0
|
19天前
|
存储 安全 算法
c++动态内存管理(一)
C++ 动态内存管理 在 C++ 中,动态内存管理是一个核心概念,它允许在运行时分配和释放内存。以下是 C++ 动态内存管理需要掌握的关键知识点:
123 0
|
10月前
|
存储 编译器 C语言
动态内存管理(1)
动态内存管理(1)
|
11月前
动态内存管理(二)
动态内存管理
36 0
|
6月前
|
程序员 编译器 C语言
动态内存管理(2)
动态内存管理(2)
36 0
|
6月前
|
程序员 C语言 C++
动态内存管理-2
动态内存管理
21 0