动态内存管理

为什么要有动态内存分配?

我们已有的内存开辟方式:

c 复制代码
int val = 20;//在栈上开辟4个字节的空间
char arr[20] = { 0 };//在栈上开辟20个字节的空间

这些内存开辟方式有一定的限制:空间开辟大小是固定的,变量或数组的空间一旦确定了大小不能改变。

动态内存开辟的优点

  • 开辟空间的大小更加灵活
  • 可以自己维护内存的使用和生命周期

动态内存开辟的空间位于堆区

动态内存分配函数

mallocfree

malloc

malloc是 C 语言库函数,头文件为stdlib.h,功能是动态内存开辟 。

c 复制代码
void* malloc(size_t size);

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

  • 如果开辟成功 ,则返回一个指向开辟好空间的指针
  • 如果开辟失败 ,则返回⼀个NULL指针 ,因此malloc返回值⼀定要做检查
  • 开辟的内存块的大小以字节为单位。
  • 返回值的类型是void*,所以malloc函数并不知道开辟空间的类型,在使用的时候使用者自己来决定。
  • 如果参数size0malloc的行为是标准是未定义的,取决于编译器。
free

free是 C 语言库函数,头文件为stdlib.h,功能是动态内存的释放和回收 。

c 复制代码
void free (void* ptr);

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

  • ptr是动态空间的起始地址。
  • 如果参数ptr指向的空间不是动态开辟的,那free函数的行为是未定义的。
  • 如果参数ptrNULL指针,则函数什么事都不做。
c 复制代码
#include<stdio.h>
#include<stdlib.h>

int main()
{
	//申请存放10个整型的内存的空间
	int* p = (int*)malloc(10 * sizeof(int));
	
	//判断
	if (!p)
	{
		perror("malloc");
		return 1;//失败返回
	}

	//使用内存
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		*(p + i) = i;
	}
	for (i = 0; i < 10; i++)
	{
		printf("%d ", *(p + i));
	}

	//释放内存
	free(p);//释放内存后p就是野指针
	p = NULL;

	return 0;//成功返回
}

注意:

程序结束的时候,即使没有使用free函数,操作系统也会主动回收这块内存空间。

糟糕的是,程序没有结束运行,也不使用free函数,申请的内存空间也不使用。

calloc

calloc函数是 C 语言库函数,头文件为stdlib.h,功能是动态内存分配。

c 复制代码
void* calloc (size_t num, size_t size);
  • 函数的功能是为num个大小为size的元素开辟⼀块空间,并且把空间的每个字节初始化为 0
  • 与函数malloc的区别只在于calloc会在返回地址之前把申请的空间的每个字节初始化为全0
c 复制代码
#include<stdio.h>
#include<stdlib.h>

int main()
{
	//申请存放10个整型的内存的空间
	int* p = (int*)calloc(10, sizeof(int));

	//判断
	if (!p)
	{
		perror("calloc");
		return 1;//失败返回
	}

	//使用内存
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		printf("%d ", *(p + i));//输出 0 0 0 0 0 0 0 0 0 0
	}
	
	//释放内存
	free(p);//释放内存后p就是野指针
	p = NULL;

	return 0;//成功返回
}

如果我们对申请的内存空间的内容要求初始化 ,那么可以使用 calloc函数

realloc

realloc函数是 C 语言库函数,头文件为stdlib.h,功能是对动态开辟内存大小的调整。

c 复制代码
void* realloc (void* ptr, size_t size);
  • ptr是要调整的内存地址。
  • size是调整之后的大小,单位为字节
  • realloc函数在调整内存空间时存在两种情况:
    • 情况 1: 原有空间之后有足够大的空间
    • 情况 2: 原有空间之后没有足够大的空间

情况 1:

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

情况 2:

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

如果没有合适大小的连续空间,则返回失败。

  • 如果调整成功,返回值为调整之后的内存起始位置。
  • 如果调整失败,返回值为NULL指针。因此realloc返回值⼀定要做检查
c 复制代码
#include<stdio.h>
#include<stdlib.h>

int main()
{
	//申请空间
	int* ptr = (int*)malloc(100);

	//判断
	if (!ptr)
	{
		perror("malloc");
		return 1;//失败返回
	}
	else
	{
		//业务处理
	}
	
	//扩展容量
	
	/*
	错误写法:
	int* p = realloc((void*)ptr, 100);
	若调整失败,则会丢失原来的数据
	*/

	int* p = NULL;
	p = realloc((void*)ptr, 100);
	if (p)
	{
		perror("realloc");
		return 2;//失败返回
	}
	ptr = p;
	
	//释放内存
	free(ptr);
	p = NULL;
	ptr = NULL;

	return 0;//成功返回
}

常见的动态内存的错误

NULL指针的解引用操作

c 复制代码
void test()
{
	int* p = (int*)malloc(INT_MAX / 4);
	*p = 20;//如果p的值是NULL,就会有问题
	free(p);
}

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

c 复制代码
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);
}

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

c 复制代码
void test()
{
	int a = 10;
	int* p = &a;
	free(p);//使用free释放非动态开辟的内存-err
}

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

c 复制代码
#include<stdio.h>
#include<stdlib.h>

int main()
{
	int* p = malloc(100);
	if (p)
	{
		return 1;
	}
	int i = 0;
	for (i = 0; i < 5; i++)
	{
		*p = i + 1;
		p++;
	}
	free(p);//p不再指向动态内存的起始位置
	return 0;
}

注意: free的参数部分要传递的是要释放的空间的的起始地址。

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

c 复制代码
void test()
 {
    int *p = (int *)malloc(100);
    free(p);//释放后p为野指针

    //...
    
    free(p);
    p = NULL
}

注意: free函数释放内存后要把指针变为空指针,free函数的参数为NULL则什么都不做。

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

c 复制代码
#include<stdio.h>
#include<stdlib.h>

void test()
{
	//开辟
	int*p = (int*)malloc(40);
	if (p == NULL)
		return;
	
	//使用
	if(1)//某条件发生,则退出程序,并且未释放内存
		return;

	//释放
	free(p);
	p = NULL;
}

int main()
{
	test();//p局部变量销毁,无法找到并释放内存,造成内存泄漏
	return 0;
}

注意:动态开辟的内存一定要释放,并正确释放。

柔性数组

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

例如:

c 复制代码
struct S
{
	int i;
	int a[0];
};

有些编译器可能会报错无法编译,也可以改成以下形式:

c 复制代码
struct S
{
	int i;
	int a[];
};

柔性数组的特点

  • 结构中的柔性数组成员前面必须至少一个其他成员。
  • sizeof 返回的结构体大小不包括柔性数组的内存。
  • 包含柔性数组成员的结构用malloc函数进行内存的动态分配,并且分配的内存应该大于结构的大小,以适应柔性数组的预期大小。
c 复制代码
#include<stdio.h>

struct S
{
	int i;
	int a[];
};

int main()
{
	printf("%zd\n", sizeof(struct S));//输出 4
	return 0;
}

柔性数组的使用

c 复制代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

struct S
{
	int i;
	int a[];
};

int main()
{
	//申请内存
	struct S* ps = (struct S*)malloc(sizeof(struct S) + 10 * sizeof(int));
	if (ps)
	{
		perror("malloc");
		return 1;
	}
	//使用内存
	ps->i = 100;
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		ps->a[i] = i + 1;
	}
	//调整内存
	struct S* ptr = (struct S*)realloc(ps, sizeof(struct S) + 20 * sizeof(int));
	if (ptr)
	{
		perror("realloc");
		return 2;
	}
	ps = ptr;
	
	//...

	//释放内存
	free(ps);
	ps = NULL;
	ptr = NULL;

	return 0;
}

柔性数组的优势

c 复制代码
//代码一
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

struct S
{
	int i;
	int a[];
};

int main()
{
	//申请内存
	struct S* ps = (struct S*)malloc(sizeof(struct S) + 10 * sizeof(int));
	if (!ps)
	{
		perror("malloc");
		return 1;
	}
	//使用内存
	ps->i = 100;
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		ps->a[i] = i + 1;
	}
	//调整内存
	struct S* ptr = (struct S*)realloc(ps, sizeof(struct S) + 20 * sizeof(int));
	if (!ptr)
	{
		perror("realloc");
		return 2;
	}
	ps = ptr;

	//...

	//释放内存
	free(ps);
	ps = NULL;
	ptr = NULL;

	return 0;
}
c 复制代码
//代码二
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

struct S
{
	int i;
	int* p;
};

int main()
{
    //申请内存
	struct S* ps = (struct S*)malloc(sizeof(struct S));
	if (!ps)
	{
		perror("malloc");
		return 1;
	}
	int* ptr = (int*)malloc(10 * sizeof(int));
	if (!ptr)
	{
		perror("malloc");
		return 2;
	}
    //使用内存
	ps->p = ptr;
	ps->i = 100;
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		*(ps->p + i) = i + 1;
	}
    //调整内存
	ptr = (int*)realloc(ps->p, 20 * sizeof(int));
	if (!ptr)
	{
		perror("realloc");
		return 3;
	}
	ps->p = ptr;

    //...

    //释放内存
    free(ps);
    ps = NULL;
	free(ps->p);
	ps->p = NULL;
	ptr = NULL;
    
	return 0;
}

上述代码 1代码 2可以完成相同的功能,但代码 1有两个优势:

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

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

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

连续的内存有益于提高访问速度,也有益于减少内存碎片。

总结C/C++中程序内存区域划分

  1. 栈区(stack):在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束时 这些存储单元自动被释放。栈内存分配运算内置于处理器的指令集中,效率很高,但是分配的内存容量有限。栈区主要存放运行函数而分配的局部变量、函数参数、返回数据、返回地址等。
  2. 堆区(heap):一般由程序员分配释放,若程序员不释放,程序结束时可能由OS回收。分配方式类似于链表。
  3. 数据段(静态区)(static)存放全局变量、静态数据。程序结束后由系统释放。
  4. 代码段:存放函数体(类成员函数和全局函数)的二进制代码和只读常量。

动态内存笔试题分析

题目一

c 复制代码
#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);//此处str为传值调用,str仍为NULL
	strcpy(str, "hello world");//对空指针str进行解引用,非法访问内存,程序崩溃
	printf(str);
}

int main()
{
	test();
	return 0;
}

正确写法 1:

c 复制代码
#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;
}

正确写法 2:

c 复制代码
#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;
}

题目二

c 复制代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char* GetMemory(void)
{
	char p[] = "hello world";
	return p;//程序结束,空间回收
}
void Test(void)
{
	char* str = NULL;
	str = GetMemory();//str为野指针
	printf(str);
}

int main()
{
	Test();
	return 0;
}

题目三

c 复制代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void Test(void)
{
	char* str = (char*)malloc(100);
	strcpy(str, "hello");
	free(str);//str为野指针
	if (str != NULL)
	{
		strcpy(str, "world");//对野指针str进行解引用,非法访问内存,程序崩溃
		printf(str);
	}
}

int main()
{
	Test();
	return 0;
}
相关推荐
laocooon5238578862 小时前
win操作系统安装C++语言开发环境之一, vscode +MinGW ,流程
c语言
奔跑吧邓邓子2 小时前
解锁Vscode:C/C++环境配置超详细指南
c语言·c++·vscode·配置指南
小柯博客10 小时前
从零开始打造 OpenSTLinux 6.6 Yocto 系统(基于STM32CubeMX)(十二)
c语言·stm32·单片机·嵌入式硬件·php·嵌入式
乄夜14 小时前
嵌入式面试高频(5)!!!C++语言(嵌入式八股文,嵌入式面经)
c语言·c++·单片机·嵌入式硬件·物联网·面试·职场和发展
乖乖是干饭王16 小时前
Linux系统编程中的_GNU_SOURCE宏
linux·运维·c语言·学习·gnu
weixin_4786897617 小时前
C++ 对 C 的兼容性
java·c语言·c++
待什么青丝17 小时前
【TMS570LC4357】之相关驱动开发学习记录2
c语言·arm开发·驱动开发·单片机·学习
小柯博客17 小时前
从零开始打造 OpenSTLinux 6.6 Yocto 系统(基于STM32CubeMX)(九)
c语言·stm32·单片机·嵌入式硬件·物联网
CodeWithMe19 小时前
【C/C++】namespace + macro混用场景
c语言·开发语言·c++
SY师弟21 小时前
台湾TEMI协会竞赛——0、竞赛介绍及开发板介绍
c语言·单片机·嵌入式硬件·嵌入式·台湾temi协会