C中一道关于内存的思考题


昨天面试的时候不太确定,回来试了一下,当时虽然大方向是对的,但是一些小细节还是回答的不够好


分别运行下面的Test,会出现什么情况:

void GetMemory(char *p)
{
	p = (char *)malloc(100);
}
void Test1(void)
{
	char *str = NULL;
	GetMemory(str);
	strcpy(str, "hello world");
	/*运行上一句时程序崩溃,因为GetMemory(char *p)不能传递动态内存,原因是GetMemory(str)的参数是值传递,不会改变str的值*/
	printf(str);
}
char *GetMemory(void)
{
	char p[] = "hello world";
	return p;
}
void Test2(void)
{
	char *str = NULL;
	str = GetMemory();
	printf(str);
	/*乱码,*GetMemory()返回的是栈指针,在函数结束时已经栈退解,内容未知*/
}
void GetMemory2(char **p, int num)
{
	*p = (char *)malloc(num);
}
void Test3(void)
{
	char *str = NULL;
	GetMemory2(&str, 100);
	strcpy(str, "hello");
	/*能正确输出"hello",但有一个问题,内存泄露,malloc的内存没有free*/
	printf(str);
}
void Test4(void)
{
	char *str = (char *)malloc(100);
	strcpy(str, "hello");
	free(str);	
	if (str == NULL)
	{
		strcpy(str, "world");
		printf(str);
	}
	/*可以输出"world",因为free之后str变为了野指针,但是并没有置为NULL,因此还会继续执行下面的内容*/
}


以上代码均经过测试,win7+VS2013


—————————————————————————————————————————————————————————————————

//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。

转载请注明出处:http://blog.csdn.net/qq844352155

author:天下无双

Email:[email protected]

2015-6-30

于广州天河荷光路

——————————————————————————————————————————————————————————————————





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章