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

於廣州天河荷光路

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





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