1 What will happen after running the "Test"?
#include <iostream.h>
void GetMemory(char *p, int num)
{
p = (char *)malloc(sizeof(char) * num);
}
int main()
{
char *str = NULL;
GetMemory(str, 100);
strcpy(str, "hello");
return 0;
}
分析:由於void GetMemory(char *p, int num)中的*p實際上是主函數中的一個str的一個副本,編譯器總是要為函數的每個參數製作臨時副本。在本倒中,p申請了新的記憶體,只是把p把指的記憶體位址改變了,但str絲毫未變。因為GetMemory沒有傳回值,因此str並不指向p所申請的那段記憶體,所以函數GetMemory並不能輸出任何東西。事實上,每執行一次GetMemory就會申請一塊記憶體,但申請的記憶體卻不能有效釋放,結果是記憶體一直被獨佔,最終造成記憶體泄露。
答案:程式崩潰。因為GetMemory並不能傳遞動態記憶體,Test函數中的str一直都是NULL。
//---------------------------------------------------------------------------------------------------
以下是正常的申請方式:
方法一:用指標參數去申請記憶體時,應用採用指向指標的指標,把str的地址傳給函數GetMemory
#include <iostream.h>
void GetMemory(char **p, int num)
{
*p = (char *)malloc(sizeof(char) * num);
}
int main()
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
std::cout << *str << std::endl;
std::cout << str << std::endl;
std::cout << &str << std::endl;
return 0;
}
方法二:用函數傳回值為指標類型來傳遞動態記憶體
#include <iostream>
char *GetMemory(char *p, int num)
{
return p = (char *)malloc(sizeof(char) * num);
}
int main()
{
char *str = NULL;
str = GetMemory(str, 100);
strcpy(str, "hello");
std::cout << *str << std::endl;
std::cout << str << std::endl;
std::cout << &str << std::endl;
return 0;
}
//------------------------------------------------------------------------------------------------
What will happen after running the "Test"?
#include <iostream>
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
int main()
{
char *str = NULL;
str = GetMemory();
std::cout << str << std::endl;
return 0;
}
答案:可能是亂碼,也有可能是正常輸出。因為GetMemory返回的是指向“棧記憶體”的指標,該指標的地址不是NULL,但其原來的內容已經被清除,新內容不可知。
//------------------------------------------------------------------------------------------------
【記憶體操作及問題相關知識點】為了能徹底解決動態記憶體傳遞的問題,我們回顧一下記憶體管理的知識要點.
記憶體配置方式有三種:
從靜態儲存地區分配。記憶體在程式編譯的時候就已經分配好,這塊記憶體在程式的整個運行期間都存在。例如全域變數,static變數。
從堆上分配,亦稱動態記憶體分配。程式在啟動並執行時候用malloc或new申請任意多少的記憶體,程式員自己負責在何時用free或delete釋放記憶體。動態記憶體的生存期由我們決定,使用非常靈活。
在棧上建立。在執行函數時,函數內局部變數的儲存單元都可以在棧上建立,函數執行結束時這些儲存單元自動被釋放。棧記憶體配置運算內建於處理器的指令集中,效率很高,但是分配的記憶體容量有限。
原網址:http://blog.csdn.net/seuzyq/archive/2009/10/06/4636849.aspx