动态内存管理2


1、常见的动态内存错误

1.1对NULL指针的解引用操作

在这里插入图片描述

INT_MAX是一个很大的数,没有足够的空间,所以malloc返回一个空指针


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

int main()
{
	int* p = (int*)malloc(40);
	if (p == NULL)
	{
		printf("%s\n", strerror(errno));
		return 1;
	}
	//方式
	int i = 0;
	for (i = 0; i <= 10; i++)
	{
		p[i] = i;
	}
	free(p);
	p = NULL;
	return 0;
}

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

int main()
{
	int a = 10;
	int* p = &a;
	free(p);
	p = NULL;
	return 0;
}

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

int main()
{
	int* p = (int*)malloc(40);
	if (p == NULL)
	{
		printf("%s\n", strerror(errno));
		return 1;
	}
	//使用
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		*p = i;
		p++;
	}
	free(p);
	p = NULL;
	//释放
	return 0;
}

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

int main()
{
	int* p = (int*)malloc(40);
	free(p);
	free(p);
	return 0;
}

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

void test()
{
	int* p = (int*)malloc(100);
	if (NULL != p)
	{
		*p = 20;
	}

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

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


2、几个经典的面试题

题目1

void GetMemory(char *p)
{
 p = (char *)malloc(100);
}
void Test(void)
{
 char *str = NULL;
 GetMemory(str);
 strcpy(str, "hello world");
 printf(str);
}

请问运行Test 函数会有什么样的结果?
str作为形参传入到GetMemory函数里面,创建了一块100字节的空间给p,出作用域以后p销毁了,str仍然是空指针,导致strcpy的时候会崩溃(strcpy进行实现时需要解引用前面一个参数)

修改:传地址,GetMemory传入&str,用char** p 的二级指针接收这个地址


题目2

char *GetMemory(void)
{
 char p[] = "hello world";
 return p;
}
void Test(void)
{
 char *str = NULL;
 str = GetMemory();
 printf(str);
}

请问运行Test 函数会有什么样的结果?
调用GetMemory后,返回p原来指向hello world的地址,但是出作用域以后p被销毁,GetMemory传过来的是一块未知的区域的首地址


题目3:

void GetMemory(char **p, int num)
{
 *p = (char *)malloc(num);
}
void Test(void)
{
 char *str = NULL;
 GetMemory(&str, 100);
 strcpy(str, "hello");
 printf(str);
}

请问运行Test 函数会有什么样的结果?
代码设计还算合理,但是没有
free(str);
str = NULL;


题目4:

void Test(void)
{
 char *str = (char *) malloc(100);
 strcpy(str, "hello");
 free(str);
 if(str != NULL)
 {
 strcpy(str, "world");
 printf(str);
 }
}

请问运行Test 函数会有什么样的结果?
解引用了野指针


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不爱吃鱼的怪兽

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

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

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

打赏作者

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

抵扣说明:

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

余额充值