C++,这样内存会不会漏洞?

来源:百度知道 编辑:UC知道 时间:2024/09/28 01:17:48
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}

泄漏,指针 p 不会返回分配的内存
改成

char *GetMemory(void)
{
return (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
str=GetMemory();
strcpy(str, "hello world");
printf(str);
}

str通过GetMemory得不到新分配的地址
GetMemory(char **p)
{
*p = (char *)malloc(100);
}
就可以了

没有free

p在函数结束是释放,但是他指向的内容,不会释放。

会,TEST()中的str的值并不会在GETMEMORY()中改变。