【小練習】指標與引用:傳遞動態記憶體2
阿新 • • 發佈:2018-12-13
1.練習程式碼-程式碼中的問題是什麼?
#include <iostream>
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;
}
2.關鍵點分析
#include <iostream>
void GetMemory(char *p, int num)
{
p = (char *)malloc(sizeof(char) * num);
//錯誤1:函式中的*p是主函式str指標的一個副本,str本身並沒有申請到記憶體
//錯誤2:函式執行完畢後p指標被釋放,其對應的記憶體空間無法在函式外被釋放,導致記憶體洩漏
}
int main()
{
char *str = NULL;
GetMemory(str, 100);
strcpy(str, "Hello");
return 0;
}