C++指针内存

这是一个关于C++指针的问题,思考了一下

void GetMemory(char *p, int num){

  p = (char*) malloc (sizeof(char) * num);

}

void Test(void) {

  char *str = NULL;

  GetMemory(str,100);//str 仍为NULL 

  strcpy(str, "hello");  //运行错误

}

这个p等同于指针值传递,只是将p的值传递进去,然后申请内存

编译器会为函数每个参数制作临时副本,p的副本_p = p;

如果函数体修改了_p的内容,就导致p的内容也相应修改。

如果不修改_p,p也不变。反而每执行一次就泄露一块内存。

void GetMemory2(char **p, int num){

  *p = (char*)malloc(sizeof(char) * num);

}

void Test2(void){

  char *str = NULL;

  GetMemory(&str,100);//参数是&tr

  strcpy(str,"hello");

  cout<<str<<endl;

  free(str);

}

这是使用指向指针的指针来申请内存的,理解参考:http://www.cnblogs.com/dzry/archive/2011/05/12/2044835.html

这里p相当于指向了str,p申请了内存就相当于str申请了内存,个人觉得有点难理解

char *GetMemory3(int num){

  char *p = (char*)malloc(sizeof(char) * num);

  return p;

}

void Test3(void){

  char *str = NULL;

  str = GetMemory3(100);

  strcpy(str,"hello");

  cout<<str<<endl;

  free(str);

}

这个就是在堆中申请了一段内存,然后返回给str,对于堆,栈,静态区的理解参考:http://my.oschina.net/liangtee/blog/126728

在GetMemory3中free(P)后,程序还是可以运行的,所以个人觉得free()释放内存是程序运行解释之后的,而不是马上就在函数运行是释放

参考:http://www.bccn.net/Article/kfyy/cyy/jszl/200608/4238_2.html

char *GetString(void){

  char p[] = "hello world";

  return p;//编译器出错

}

void Test4(void){

  char *str = NULL;

  str = GetString();//乱码

  cout<<str<<endl;

}

返回的p被系统回收了,所以是野指针。因为这里是栈申请的存储空间。

char *GetString2(void){

  char *p = "hello world";

  return p;

}

void Test5(void){

  char *str = NULL;

  str = GetString2();

  cout<<str<<endl;//输出hello world

}

p申请的是字符串常量,所以指针不变。  

对指针又加深了一点点了解

参考于: C++高质量编程指南

原文地址:https://www.cnblogs.com/george-cw/p/3629743.html