原文:http://www.cnblogs.com/madengwei/archive/2008/02/18/1072410.html
[] C C++
("wildpointer)
class Object
{
public :
Object(void){std::cout << “Initialization”<< std::endl; }
~Object(void){std::cout << “Destroy”<< std::endl; }
void Initialize(void){std:: cout << “Initialization”<< std::endl; }
void Destroy(void){ std::cout << “Destroy”<< std::endl; }
}
void UseMallocFree(void)
{
Object *ip = (Object *)malloc(sizeof(Object)); // 申請動態內存
ip->Initialize(); // 初始化
//…
ip->Destroy(); // 清除工作
free(ip); // 釋放內存
}
void UseNewDelete(void)
{
Object *ip = new Object; // 申請動態內存並且初始化
//…
Delete ip; // 清除並且釋放內存
}
void Func(void)
{
A *a = new A;
if(a == NULL)
{
return;
}
…
}
void Func(void)
{
A *a = new A;
if(a == NULL)
{
std::cout << “Memory Exhausted” << std::endl;
exit(1);
}
…
}
class A
{
public:
void Func(void){ std::cout << “Func of class A” << std::endl; }
};
void Test(void)
{
A *p;
{
A a;
p = &a; // 注意 a 的生命期
}
p->Func(); // p是“野指針”
}
void GetMemory(char *ip, int num)
{
ip = (char *)malloc(sizeof(char) * num);
}
void Test(void)
{
char *str = NULL;
GetMemory(str, 100); // str 仍然為 NULL
strcpy(str, "hello"); // 運行錯誤
}
void GetMemory(char **p, int num)
{
*ip = (char *)malloc(sizeof(char) * num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100); // 注意參數是 &str,而不是str
strcpy(str, "hello");
std::cout<< str << std::endl;
free(str);
}
用指向指針的指針申請動態內存
當然,我們也可以用函數返回值來傳遞動態內存。這種方法更加簡單,見如下示例:
char *GetMemory(int num)
{
char *ip = (char *)malloc(sizeof(char) * num);
return ip;
}
void Test(void)
{
char *str = NULL;
str = GetMemory(100);
strcpy(str, "hello");
std::cout<< str << std::endl;
free(str);
}
char *GetString(void)
{
char p[] = "hello world";
return p; // 編譯器將提出警告
}
void Test(void)
{
char *str = NULL;
str = GetString(); // str 的內容是垃圾
std::cout<< str << std::endl;
}