可以采用3中办法来解决动态内存不能传递的问题
在C语言中,可以通过采用指向指针的指针解决这个问题,可以把str的地址传给函数GetMemory.
在C++中,多了一种选择,就是传递str指针的引用;
使用函数返回值来传递动态内存;
代码如下:
#include <iostream>
using namespace std;
void GetMemory(char *p,int num)
{
p = (char*)malloc(sizeof(char)*num);
};
void GetMemory2(char **p,int num)
{
*p = (char*)malloc(sizeof(char)*num);
};
void GetMemory3(char* &p,int num)
{
p = (char *)malloc(sizeof(char)*num):
}
char *GetMemory4(int num)
{
char *p = (char*)malloc(sizeof(char)*num);
return p;
}
int main()
{
char *str1 =NULL;
char *str2 =NULL;
char *str3 =NULL;
char *str4 =NULL;
//GetMemory(str1,20);
GetMemory2(str2,20);
GetMemory3(str3,20);
str4 =GetMemory4(str4,20);
strcpy(str2,"2");
strcpy(str3,"3");
strcpy(str4,"4");
cout<<(str1==NULL?Yes:No)<<endl;
cout<<str2<<endl;
cout<<str3<<endl;
cout<<str4<<endl;
free(str2);
free(str3);
free(str4);
str2 = NULL;
str3 = NULL;
str4 = NULL;
return 0;
}
GetMemory函数并不能做任何有用的事情,由于从GetMemory函数返回时不能获得堆中内存的地址,那块堆内存就不能被继续引用,也就得不到释放,因此调用一次GetMemory函数就会产生num字节的内存泄漏。