如果函数的参数是一个指针,不要指望用该内存去申请动态内存
void GetMemory(char * p ,int num)
{
p=(char*)malloc(sizeof(char)*num);
}
void Test(void)
{
char* str=NULL;
GetMemory(str,100);
strcpy(str,"hello");
}
编译器总是要为函数的每个参数制作临时副本,指针参数p的副本是_p,编译器使_p=p.
在本例中,_p申请了新的内存,只是把_p所指的内存地址改变了,但是p丝毫未变。
事实上,每执行一次GetMemory就会泄露一块内存,没有用free释放内存.
void GetMemory2(char** p,int num)
{
*p=(char*) malloc(sizeof(char)*num);
}
void Test2(void)
{
char* str=NULL;
GetMemory2(&str,100);//注意参数是&str,不是str
strcpy(str,"hello");
cout<<str<<endl;
free(str);
}
用函数返回值传递动态内存
char * GetMemory3(int num)
{
char* p=(char*) malloc(sizeof(char)*num):
return p;
}
void Test3(void)
{
char* str=NULL;
str=GetMemory3(100);
strcpy(str,"hello");
cout<<str<<endl;
free(str);
}
强调不要用return 语句返回指向“栈内存”的指针,因为内存在函数结束时自动消亡
char * GetString(void)
{
char p[]="hello world";
return p;
}
void Test4(void)
{
char* str=NULL;
str=GetString();
cout<<str<<endl;
}
发现执行str=GetString语句后str不再是NULL指针,而是str的内容不是“hello world”而是垃圾
char* GetString2(void)
{
char* p="hello world";
return p;
}
void Test5(void)
{
char* str=NULL;
str=GetString2();
cout<<str<<endl;
}
运行虽然不会出错,但是函数GetString2的设计概念却是错误的,因为GetString2内“hello world”是常量字符串,位于静态存储区,程序生命期内恒定不变。
无论什么时候调用GetString2,返回的始终是同一个只读的内存块。