//1:传递指针的方法无效,结果导致内存泄露
void GetMemory(char *p,int num)
{
    p=(char*)malloc(num*sizeof(char));
}
int main()
{
    char *str=NULL;
    GetMemory(str,10);
    strcpy(str,"hello");
    free(str);//free 并没有起作用,内存泄露
    return 0;
}
//2:return 返回分配内存地址
char* GetMemory(char *p,int num)
{
    p=(char*)malloc(num*sizeof(char)
    return p;
}
int main()
{
    char* str=NULL;
    str=GetMemory(str,10);
    strcpy(str,"hello");
    free(str);
    return 0;
}
//3:二级指针的使用,将指针地址传递给函数,改变指针内容(即分配内存首地址)
void GetMemory(char **p,int num)
{
    *p=(char*)malloc(num*sizeof(char));
    return p;
}
int main()
{
    char *str=NULL;
    GetMemory(&str,10);
    strcppy(str,"hello");
    free(str);
    return 0;
}

 

相关文章:

  • 2021-12-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-09-09
  • 2021-10-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案