C++内存管理详解(三)

来源:互联网 发布:cad软件锁许可管理器 编辑:程序博客网 时间:2024/06/06 20:39

4、指针参数是如何传递内存的?

如果函数的参数是一个指针,不要指望用该指针去申请动态内存。示例7-4-1中,test函数的语句getmemory(str, 200)并没有使str获得期望的内存,str依旧是null,为什么?

  1. void getmemory(char *p, int num)  
  2. {  
  3.  p = (char *)malloc(sizeof(char) * num);  
  4. }  
  5. void test(void)  
  6. {  
  7.  char *str = null;  
  8.  getmemory(str, 100); // str 仍然为 null   
  9.  strcpy(str, "hello"); // 运行错误  
  10. }   
  11. 示例4.1 试图用指针参数申请动态内存 

毛病出在函数getmemory中。编译器总是要为函数的每个参数制作临时副本,指针参数p的副本是 _p,编译器使 _p = p。如果函数体内的程序修改了_p的内容,就导致参数p的内容作相应的修改。这就是指针可以用作输出参数的原因。在本例中,_p申请了新的内存,只是把_p所指的内存地址改变了,但是p丝毫未变。所以函数getmemory并不能输出任何东西。事实上,每执行一次getmemory就会泄露一块内存,因为没有用free释放内存。

如果非得要用指针参数去申请内存,那么应该改用“指向指针的指针”,见示例4.2。

  1. void getmemory2(char **p, int num)  
  2. {  
  3.  *p = (char *)malloc(sizeof(char) * num);  
  4. }  
  5. void test2(void)  
  6. {  
  7.  char *str = null;  
  8.  getmemory2(&str, 100); // 注意参数是 &str,而不是str  
  9.  strcpy(str, "hello");   
  10.  cout<< str << endl;  
  11.  free(str);   
  12. }   
  13. 示例4.2用指向指针的指针申请动态内存 

由于“指向指针的指针”这个概念不容易理解,我们可以用函数返回值来传递动态内存。这种方法更加简单,见示例4.3。

  1. char *getmemory3(int num)  
  2. {  
  3.  char *p = (char *)malloc(sizeof(char) * num);  
  4.  return p;  
  5. }  
  6. void test3(void)  
  7. {  
  8.  char *str = null;  
  9.  str = getmemory3(100);   
  10.  strcpy(str, "hello");  
  11.  cout<< str << endl;  
  12.  free(str);   
  13. }   
  14. //示例4.3 用函数返回值来传递动态内存  
  15.  

用函数返回值来传递动态内存这种方法虽然好用,但是常常有人把return语句用错了。这里强调不要用return语句返回指向“栈内存”的指针,因为该内存在函数结束时自动消亡,见示例4.4。

  1. char *getstring(void)  
  2. {  
  3.  char p[] = "hello world";  
  4.  return p; // 编译器将提出警告  
  5. }  
  6. void test4(void)  
  7. {  
  8.  char *str = null;  
  9.  str = getstring(); // str 的内容是垃圾  
  10.  cout<< str << endl;  
  11. }   
  12. //示例4.4return语句返回指向“栈内存”的指针 

用调试器逐步跟踪test4,发现执行str = getstring语句后str不再是null指针,但是str的内容不是“hello world”而是垃圾。
如果把示例4.4改写成示例4.5,会怎么样?

  1. char *getstring2(void)  
  2. {  
  3.  char *p = "hello world";  
  4.  return p;  
  5. }  
  6. void test5(void)  
  7. {  
  8.  char *str = null;  
  9.  str = getstring2();  
  10.  cout<< str << endl;  
  11. }   
  12.  示例4.5 return语句返回常量字符串 

函数test5运行虽然不会出错,但是函数getstring2的设计概念却是错误的。因为getstring2内的“hello world”是常量字符串,位于静态存储区,它在程序生命期内恒定不变。无论什么时候调用getstring2,它返回的始终是同一个“只读”的内存块。