栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

关于动态内存开辟的几个经典面试题

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于动态内存开辟的几个经典面试题

题目1

运行会有什么样的结果?

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

运行结果:

 char* str = NULL;
 GetMemory(str);

str在这里表示传值调用,p代表形参,形参的改变不影响实参。

改正1:

#include
#include
#include
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;

通过二级指针接收指针str的地址。

指针变量也是变量,在这里,str并不代表地址。

改正2:

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

通过返回值直接找到动态开辟空间的位置。

题目2

运行完之后会出现什么情况?

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

运行结果:

 错误原因:

     char p[] = "hello world";  ------p是在栈空间上创建的局部变量,具有生命周期,当这个函数结束返回‘h’的地址后,这块空间就销毁了,当再次打印时,就会打印随机值。

改正:

#include
#include
#include
char* GetMemory(void)
{
	static  char p[] = "hello world";
	return p;
}
void Test(void)
{
	char* str = NULL;
	str = GetMemory();
	printf(str);
}
int main()
{
	Test();
	return 0;
}

    static  char p[] = "hello world";

把所打印的内容放到静态区上,这样数组p的生命周期变长。不会在这次函数调用后就销毁了。


题目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);
}

运行结果:

 通过结果感觉结果没什么问题,但实际上这个代码是有问题的。

对动态内存开辟的空间没有释放,将会造成内存泄漏。这是不安全的。

改正:

#include
#include
#include
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

下面代码运行结果是什么?

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

运行结果: 

运行结果看着是正确的,但是代码是存在很大问题的。

    free(str);  //free释放str指向的空间后,并不会把str置为NULL

改正:

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

在这里考察的事free后是否将指针置为NULL,应该和free释放位置没太大关联。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/290500.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号