利用函数申请内存的几个问题

来源:互联网 发布:开盘数据恢复成功率 编辑:程序博客网 时间:2024/06/05 22:42

本文转自:http://buptdtt.blog.51cto.com/2369962/832201

在下面的例子中,GetMemory1是想通过形参返回动态申请的内存的地址,这个时候只能用二重指针,如GetMemory2所示。还可以通过return语句将申请的内存地址返回,即:把GetMemory1的返回值类型改成char*,在函数体内添加语句: return p;。

#include<stdio.h>    #include <iostream>    using namespace std;     void GetMemory1(char *p)      {          p = (char *)malloc(100);      }      void Test1(void)      {          char *str = NULL;          GetMemory1(str);           strcpy(str, "hello world"); //报内存错误,此时str仍然是空        printf(str);      }         void GetMemory2(char **p, int num)//用二重指针是正确的      {          *p = (char *)malloc(num);      }      void Test2(void)      {          char *str = NULL;          GetMemory2(&str, 100);          strcpy(str, "hello");            printf(str);//输出hello但是有内存泄漏         }         char *GetMemory3(void)      {            char p[] = "hello world";  //p[]存在于栈里边.函数结束后释放        return p;    }      void Test3(void)      {          char *str = NULL;          str = GetMemory3();          printf(str); //输出不可预测,因为GetMemory 返回的是指向“栈内存”的指针,                     //该指针的地址不是 NULL ,但其原现的内容已经被清除,新内容不可知。      }         char *GetMemory4(void)      {            char *p = "hello world";  //存放在字符串常量区,程序结束后才释放        return p;    }      void Test4(void)      {          char *str = NULL;          str = GetMemory4();          printf(str); //输出hello world      }         void Test5(void)      {          char *str = (char *) malloc(100);          strcpy(str, "hello");          free(str);   // str 所指的内存被释放,但是str的值仍然不变,原来的内存变为“垃圾”内存</span>      if(str != NULL) // 没有起到防错作用</span>      {              strcpy(str, "world");    //          printf(str);  //        }      }    

以上的程序涉及到C++中变量的存储位置和有效期

1、栈区:由系统进行内存管理,用于存储函数的参数值、局部变量,函数结束后释放。
2、堆区:由程序员分配和释放,new、malloc
3、全局区、静态区:存放全局变量和静态变量。

4、字符串常量区:用于存放字符串常量,程序结束后由系统释放。

===================================================================

static关键字的在C/C++中的作用主要变现在,它影响了变量的visibility和duration:http://stackoverflow.com/questions/943280/difference-between-static-in-c-and-static-in-c