#include#include void GetMemory(char* p) { p = (char*)malloc(100); } int main() { char* str = NULL; GetMemory(str); strcpy(str, "hello world"); printf(str); return 0; }
上述代码运行会产生什么结果?
可以看到程序引发异常,原因就是因为malloc函数是在堆上开辟空间的,函数的变量是在栈上开辟空间的,str变量开始指向NULL,函数传参发生形参实例化,会将str变量拷贝到p变量,p变量指向NULL,经过malloc函数在堆上开辟空间,p指向堆空间的地址,实际上p变量指向的地址str并没有接受到,因此会并没有空间接受字符串“hello world”,发生错误拷贝,这是第一个错误。
第二个错误是p是临时变量,GetMemory函数运行结束后会释放掉临时变量p,但是堆上的空间并没有使用free函数释放调,会发生内存泄露风险。
解决方案我给了两个:
方案一:将临时变量指针返回给str接收。
char* GetMemory1(char* p) {
p = (char*)malloc(100);
return p;
}
int main()
{
char* str = NULL;
str = GetMemory1(str);
strcpy(str, "hello world");
printf(str);
free(str);
return 0;
}
方案二:使用二级指针,传入函数的是str的地址,对p解引用表示p的内容也就是str,于是开辟的空间地址可以str接收到。
void GetMemory2(char** p) {
*p = (char*)malloc(100);
}
int main()
{
char* str = NULL;
GetMemory2(&str);
strcpy(str, "hello world");
printf(str);
free(str);
return 0;
}



