64,685
社区成员
发帖
与我相关
我的任务
分享
char *GetMemory(void)
{
char p[] = "hello world"; //这里P以及“hello world”都是在栈区,所以函数退出时,往下看
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory(); //这里指针赋值是可以得到P的正确地址的,只是,地址里的内容以及被释放掉了,所以得不到正确结果!
printf(str);
}
char *GetMemory(void)
{
char *p= "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
int main ()
{
Test();
return 0;
}
char *strcpy(char *strDest, const char *strSrc); //strDest 是调用函数传过来的,即使是栈上面的也是调用函数栈上面的,这个函数是返回给调用函数的, 也就是说strDest是调用者维护的。所以保证这个没有问题。
{
assert((strDest!=NULL) && (strSrc !=NULL));
char *address = strDest;
while( (*strDest++ = * strSrc++) != ‘\0’ )
NULL ;
return address ;
}
void GetMemory(char *p)
{
p = (char *)malloc(100);//实际是两个指针。传过来的指针p,然后进入这个函数后,会拷贝一个_p的指
//针。在这个函数里操作的是_p.所以,只是_p改变了。并没有改变p.(p这才是真真的str ,_p只是拷贝).
}
void Test(void)
{
char *str = NULL;
GetMemory(&str); //每getMemory()一下,就去掉一块内存,导致 内存泄露。
strcpy(str, "hello world");
printf(str);
}
下面是两种解决方法:
[code=C/C++]
void GetMemory(char **p)
{
*p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str);
strcpy(str, "hello world");
printf(str);
}
void GetMemory(char *&p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
void GetMemory(char *p)
{
p = (char *)malloc(100);//实际是两个指针。传过来的指针p,然后进入这个函数后,会拷贝一个_p的指针。在这个函数里操作的是_p.所以,只是_p改变了。并没有改变p.(p这才是真真的str ,_p只是拷贝).
}
void Test(void)
{
char *str = NULL;
GetMemory(&str);
strcpy(str, "hello world");
printf(str);
}