【动态内存管理】动态内存分配、常见错误、经典笔试题、柔性数组


一、动态内存分配

1、为什么存在动态内存分配

  1. 空间开辟大小是固定的
  2. 数组在声明的时候,必须指定数组的长度,它所需要的内存在编译时分配
  1. 堆区
  2. malloc calloc realloc free

二、malloc

在堆区上申请size_t大小的空间 返回这块空间的起始位置

void* malloc(size_t t);

1、malloc、free

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

  1. 如果开辟成功,则返回一个指向开辟好空间的指针。
  2. 如果开辟失败,则返回一个NULL指针,因此malloc的返回值一定要做检查。
  3. 返回值的类型是 void* ,所以malloc函数并不知道开辟空间的类型,具体在使用的时候使用者自己来决定。
  4. 如果参数 size 为0,malloc的行为是标准是未定义的,取决于编译器。

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

  1. 如果参数 ptr 指向的空间不是动态开辟的,那free函数的行为是未定义的。
  2. 如果参数 ptr 是NULL指针,则函数什么事都不做。
#include <stdio.h>
#include <stdlib.h>

int main()
{
	// 1. 开辟空间
	int* p = (int*)malloc(40); // 申请40大小空间 把起始地址强转为int* 赋给p

	if (p == NULL)
	{
		return -1;
	}
	// 开辟成功了 可以使用
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		*(p + i) = i;
	}

	// 2. 释放空间
	free(p);
	p = NULL; // 

	return 0;
}

2、calloc

void* calloc (size_t num, size_t size);

2.1、与malloc 的区别

malloc函数只负责在堆区申请空间,并且返回起始地址,不初始化空间
calloc函数在堆区上申请空间,并且在返回起始地址之前把申请的每个字节初始化为0

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
	int* p = (int*)calloc(10, sizeof(int));
	if (p == NULL)
	{
		printf("%s\n", strerror(errno));
		return -1;
	}
	// 申请成功
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		printf("%d ", *(p + i));
	}

	// 释放空间
	free(p);
	p = NULL;

	return 0;
}

3、realloc

让动态内存管理更加灵活

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

ptr 是要调整的内存地址
size 调整之后新大小
返回值为调整之后的内存起始位置。
这个函数调整原内存空间大小的基础上,还会将原来内存中的数据移动到 新 的空间

两种情况:

  1. 后面空间大小够用,直接在后面开辟
  2. 空间不够,在堆空间上另找一个合适大小的连续空间来使用,这样函数返回的是一个新的内存地址
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
	int* p = (int*)calloc(10, sizeof(int));
	if (p == NULL)
	{
		printf("%s\n", strerror(errno));
		return -1;
	}
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		*(p + i) = i;
	}

	// 空间不够大,增加空间至20int
	int* ptr = (int*)realloc(p, 20 * sizeof(int));
	if (ptr != NULL)
	{
		p = ptr;
	}
	else
	{
		return -1;
	}
	// 增加成功,使用
	for (i = 10; i < 20; i++)
	{
		*(p + i) = i;
	}
	for (i = 0; i < 20; i++)
	{
		printf("%d ", *(p + i));
	}

	free(p);
	p = NULL;

	return 0;
}

4、常见错误

4.1、 对malloc返回值判断
int* p = (int*)malloc(20);
*p = 0; // 有风险
#include <stdio.h>
#include <stdlib.h>

int main()
{
	int* p = (int*)malloc(20);

	if (p == NULL)
	{
		return -1;
	}
	*p = 0;

	return 0;
}
4.2、对动态内存空间的越界访问
#include <stdio.h>
#include <stdlib.h>

int main()
{
	int* p = (int*)malloc(200);

	if (p == NULL)
	{
		return -1;
	}

	int i = 0;
	for (i = 0; i < 80; i++)
	{
		*(p + i) = 1;
	}
	
	for (i = 0; i < 80; i++)
	{
		printf("%d ", *(p + i));
	}

	free(p);
	p = NULL;

	return 0;
}
4.3、释放非动态内存空间
int main()
{
	int a = 10;
	int* p = &a;

	free(p); // err
	p = NULL;

	return 0;
}
4.4、使用free释放一块动态开辟内存的一部分

改变了p 不再指向起始位置 此时释放的不在 起始位置

#include <stdio.h>
#include <stdlib.h>

int main()
{
	int* p = (int*)malloc(10 * sizeof(int));
	if (p == NULL)
	{
		return -1;
	}

	int i = 0;
	for (i = 0; i < 10; i++)
	{
		*p++ = 1;
	}

	free(p);
	p = NULL;

	return 0;
}
4.5、对同一块动态内存多次释放
int main()
{
	int* p = (int*)malloc(40);
	if (p == NULL)
	{
		return -1;
	}

	free(p);
	free(p); // err
}

int main()
{
	int* p = (int*)malloc(40);
	if (p == NULL)
	{
		return -1;
	}

	free(p);
	p = NULL;

	free(p); // ok
}
4.6、动态开辟内存忘记释放(内存泄漏)

在堆区上申请空间,有2种回收方式,

  1. free
  2. 程序退出时,申请的空间回收
int main()
{
	int* p = (int*)malloc(40);
	if (p == NULL)
	{
		return -1;
	}
	// 没有释放

	return 0;
}


三、经典笔试题

题目一:

#include <stdio.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;
}

在这里插入图片描述

程序会崩溃

  1. str传给p的时候,是值传递,p是str的临时拷贝,所以当malloc开辟的空间起始地址放在p中时,不会影响str,str仍是NULL
  2. 当str是NULL,strcpy想把hello world拷贝到str指向的空间时,程序就会崩溃,因为NULL指针指向的空间时不能直接访问的
  3. 存在内存泄漏,出函数销毁,无法回收空间

修改:
版本1:

#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); // char**
 
	strcpy(str, "hello world");
	printf(str);
	// 释放
	free(str);
	str = NULL;
}
 
int main()
{
	Test();
	return 0;
}

版本2:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* GetMemory(char* p)
{
	p = (char*)malloc(100);
 
	return p;
}
 
void Test(void)
{
	char* str = NULL;
 
	str = GetMemory(str);

	strcpy(str, "hello world");
 
	printf(str);
	
	free(str);
	str = NULL;
}
 
int main()
{
	Test();
	return 0;
}

题目二:

#include <stdio.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;
}

【返回栈空间地址问题】

在这里插入图片描述

#include <stdio.h>

int* test()
{
	int n = 10;

	return &n;
}
 
int main()
{
	int* p = test();

	printf("%d\n", *p);
	// 如果没有被覆盖,有可能输出10
	
	return 0;
}

题目三:

#include <stdio.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;
}

通过*p 用malloc给str在堆上开辟空间,
问题:

内存泄漏,没有free
free(str);
str = NULL;

改正:

#include <stdio.h>
#include <stdlib.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;
}

题目四:

#include <stdio.h>
#include <stdlib.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;
}

在这里插入图片描述

改正:

#include <stdio.h>
#include <stdlib.h>

void Test(void)
{
	char* str = (char*)malloc(100);

	strcpy(str, "hello");
	free(str);
	str = NULL;

	if (str != NULL)
	{
		strcpy(str, "world");
		printf(str);
	}
}

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


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

在这里插入图片描述



五、柔性数组

1、柔性数组成员

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

// 数组大小不确定,可大可小
typedef struct st_type
{
	int i;
	int a[0];//柔性数组成员
}type_a;
// 编译器报错无法编译可改成:
typedef struct st_type
{
	int i;
	int a[];//柔性数组成员
}type_a;

2、柔性数组的特点:

1. 结构中的柔性数组成员前面必须至少一个其他成员
	如 int a[] 前有 int i
2. sizeof 返回的这种结构大小不包括柔性数组的内存
#include <stdio.h>

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

int main()
{
	printf("%d\n", sizeof(struct st_type)); // 4
	return 0;
}
3. 包含柔性数组成员的结构体的使用,要配合malloc()这类动态内存分配函数使用

在这里插入图片描述


3、使用

实现之一:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

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

int main()
{
	struct st_type* ps = (struct st_type*)malloc(sizeof(struct st_type) + 10 * sizeof(int));
	// 4byte - i
	// 40byte - a

	if (ps == NULL)
	{
		printf("%s\n", strerror(errno));
		return -1;
	}
	// 开辟成功                                         
	ps->i = 100;
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		ps->a[i] = i;
	}

	for (i = 0; i < 10; i++)
	{
		printf("%d ", ps->a[i]);
	}

	// a数组的空间不够了,调为20个整型数据
	struct st_type* ptr = (struct st_type*)realloc(ps, sizeof(struct st_type) + 20 * sizeof(int));
	if (ptr == NULL)
	{
		printf("扩容空间失败");
		return -1;
	}
	else
	{
		ps = ptr;
	}

	// 使用...

	// 释放
	free(ps);
	ps = NULL;

	return 0;
}

实现之二:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

struct st_type
{
	int i; // 4
	int* a; // 4
};

int main()
{
	struct st_type* ps = (struct st_type*)malloc(sizeof(struct st_type)); // 开辟8字节空间
	ps->i = 100;
	ps->a = (int*)malloc(10 * sizeof(int));

	int i = 0;
	for (i = 0; i < 10; i++)
	{
		ps->a[i] = i;
	}
	for (i = 0; i < 10; i++)

	{
		printf("%d ", ps->a[i]);
	}

	// 调整ps->a 空间
	int* ptr = (int*)realloc(ps->a, 20 * sizeof(int));
	if (ptr == NULL)
	{
		printf("扩容失败\n");
		return -1;
	}
	else
	{
		ps->a = ptr;
	}

	// 使用...

	// 释放
	free(ps->a);
	ps->a = NULL;
	free(ps);
	ps = NULL;

	return 0;
}

柔性数组的实现的好处:
  1. 方便内存释放
    只需一次free
  2. 有利于访问速度
    malloc 次数越多,内存碎片越多
    连续的内存有益于提高访问速度,也有益于减少内存碎片
    局部性原理: 内存-高速缓存-寄存器

C语言结构体里的数组和指针

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三春去后诸芳尽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值