void GetMemory(char *p,int num)
{
p=(char *)malloc(sizeof(char)*num);
}
int main()
{
char *str=NULL;
GetMemory(str,100);
strcpy(str,"hello");
return 0;
}
注:p申请了新内存,只是把p所指的内存地址改变了,但是str丝毫未变。
所以每次GetMemory就会申请一块内存,但申请的内存却不能有效释放,结果是内存一直被独占,最终造成内存泄漏。
变形一:
#include <iostream>
using namespace std;
void GetMemory(char **p,int num)
{
*p=(char *)malloc(sizeof(char)*num);
}
int main()
{
char *str=NULL;
GetMemory(&str,100);
strcpy(str,"hello");
return 0;
}
注:传指向指针的指针,传str的地址给函数GetMemory,就行了。
*str str &str
h hello 0x22f7c
字符串某一字符的值 字符串的值 字符串的地址值
再变形:
#include <iostream>
using namespace std;
char *GetMemory(char *p,int num)
{
p=(char *)malloc(sizeof(char)*num);
return p;
}
int main()
{
char *str=NULL;
str=GetMemory(str,100);
strcpy(str,"hello");
cout<<str<<endl;
return 0;
}
注:用函数返回值来传递动态内存。
#include <iostream>
using namespace std;
void GetMemory(int *z)
{
*z=5;
}
int main()
{
int v;
GetMemory(&v);
cout<<v<<endl;
return 0;
}
注:通过传地址,GetMemory函数给地址指向的值赋值,可以实现。