一、 void GetMemory(char* p)
{
p=new char[100];
}
void test()
{
char* str=NULL;
GetMemory(str);
strcpy(str,"I love you!");
printf("%s",str);
}
结果:程序或许会崩溃
原因:GetMemory不会传递动态内存,因此str为空,从而使得strcpy运行错误。
二、char* GetMemory()
{
char p[]="I love you!";
return p;
}
void test()
{
char* str=NULL;
str=GetMemeory();
prinrf("%s",str);
}
结果:出现乱码
原因:P为局部变量,因此函数返回时,p指针的地址不为空,但它指向的内容已经清除。
三、void GetMemory(char **p, int num)
{
*p = new char[num];
}
void Test()
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, “I love you!”);
printf("%s",str);
}
结果:输出"I love you!",但会出现内存泄漏
四、void Test()
{
char *str = new char[100];
strcpy(str, “I love you!”);
delete [] str;
if(str != NULL)
{
strcpy(str, “I love you!”);
printf("%s",str);
}
}
结果:后果难以预料!因为str动态内存已经释放,str成为迷途指针。