下面c++代码怎么改,只修改getmemory函数,test函数没分配p的空间

#include
#include
#include

void GetMemory(char *p, int len)
{
p = (char *)malloc(len);
}

void Test(void)
{
char *p = NULL;
GetMemory(p, 100);
strcpy(p, "hello world");
printf("%s\n", p);
}

int main(void)
{
Test();

return 0;

}

LZ:GetMemory()函数中p的堆区地址空间已经成功分配,但是该函数运行结束后,p会被释放;因为是存放在栈区,所以你想在Test()函数中
通过赋值的形式把GetMemory()中申请的内存空间给p,这样是不会实现的,就像前面所说,GetMemory()函数运行结束后,指针p就会被释放,因此p
不再指向分配的堆区空间。所以你在test()函数中去给堆区空间拷贝值,相当于操作野指针。
下面代码已经调试好:

 #include<stdlib.h> 
#include <string.h>
#include<iostream>
using namespace std;
void GetMemory(char **p, int len)
    {
      *p = (char *)malloc(len*sizeof(char));
    }

void Test(void)
    {
    char *p = NULL;
    GetMemory(&p, 100);
    strcpy(p, "hello world");
    printf("%s\n", p);
    }
int main(void)
    {

    Test();
    return 0;
    }

已经分配了,拷贝改为memcpy试下

与没有初始化p的内容没有关系

没有初始化p内容

 void GetMemory(char *p, int len)
{
p = (char *)malloc(len);
memset(p,0,len);
}
 #include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *GetMemory(char *p, int len)
{
  p=(char *)malloc(len);
}
void Test(void)
{
char *p = GetMemory(p, 100);

strcpy(p, "hello world");
printf("%s\n", p);
}
int main(void)
{
Test();
return 0;
}

图片说明

看了大家的回答,就不用我看了