關於malloc內存申請的深入研究

在內存申請和使用上總是會出現一些莫名其妙的問題,今天剛好又碰到了,這裏總結一下。

//1.編譯可以通過,但是執行不過。卡死在註釋那一句
void test()
{
	char * str = (char *)malloc(100);
	strcpy(str,"hello");
	free(str);
	if(str != NULL)
	{
		strcpy(str,"world");
		printf("%s\n",str);//因爲str已經free,所以對str的訪問出現問題,卡死在這一步
	}
}
//---------------------------------------
//2.雙指針是OK的
void getMemory(char **p,int num)
{
	*p = (char *)malloc(num);
}

void test()
{
	char *str = NULL;
	getMemory(&str,100);
	strcpy(str,"hello");
	printf("%s\n",str);
}

//-----------------------------------------
//3.編譯通過,執行通過,返回垃圾文字。
char * getmemory()
{
	char p[] = "hello world";
	return p;
}

void test()
{
	char *str = NULL;
	str = getmemory();
	printf("%s\n", str);//因爲getmemory()中返回的是局部變量的地址,
	//所以在getmemory()執行完畢後,該變量自動釋放。所以訪問失敗。輸出一些垃圾文字。
}
//-----------------------------------------
//4.編譯通過,執行失敗。
void getmemory(char *p)
{
	p = (char *)malloc(100);//內存空間申請後,指向這一空間的指針被釋放
}

void test()
{
	char *str = NULL;
	getmemory(str);
	strcpy(str, "hello world");//str沒有空間來容納後面的字符串
	printf("%s\n", str);
}


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