您的位置:首页 > 其它

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

2012-04-12 11:24 190 查看
#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);
if(str != NULL)
{
strcpy(str, "world");
printf(str);  //输出world。free后成了野指针
}
}

void main()
{
Test5();
}

Test5为什么输出world不是很明白。

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

1、栈区:由系统进行内存管理,用于存储函数的参数值、局部变量,函数结束后释放。

2、堆区:由程序员分配和释放,new、malloc

3、全局区、静态区:存放全局变量和静态变量。

4、字符串常量区:用于存放字符串常量,程序结束后由系统释放。
本文出自 “菜鸟变身记” 博客,请务必保留此出处http://buptdtt.blog.51cto.com/2369962/832201
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: