C++内存储器分配那些事

C++内存分配那些事


#include "stdafx.h"
#include <iostream>
using namespace std;
void GetMemory1(char* p,int num)
{
	p=new char[num];
}
//如果非得要用指针参数去申请内存,那么应该改用“指向指针的指针”
void GetMemory2(char** p,int num)
{
	*p=new char[num];
}
//或者改用“指向指针的引用”
void GetMemory3(char* &p,int num)
{
	p=new char[num]; 
}
//或者改用函数返回值类传递动态内存
char* GetMemory4(int num)
{
	char *p=new char[num]; 
	return p;//必须放回的是堆内存存储区,静态全局存储区,或者返回只读的常量存储区
}
char* GetMemory5()
{
	char p[]="hello world";//数组p是栈内存,没有用new,"hello world"给数组p赋值,数组p是被分配连续的内存空间 
	return p;//return语句返回不能是指向"栈内存"的指针,因为该内存在函数结束时自动消亡
}
char* GetMemory6()
{
	char* p="hello world";//"hello world"是字符串常量,位于常量存储区,它在程序生命期内恒定不变。无论什么时候调用GetMemory6,它返回的始终是同一个“只读”的内存块。
	return p;
}
void test()
{
// 	char* str=NULL;
// 	GetMemory1(str,100);//str仍然为NULL
// 	strcpy(str,"hello");//运行有误
	// 	cout<<str<<endl;
// 	delete [] str; 
// 	str=NULL;
	
// 	char* str=NULL;
// 	GetMemory2(&str,100);
// 	strcpy(str,"hello");
	// 	cout<<str<<endl;
// 	delete [] str; 
// 	str=NULL;

// 	char* str=NULL;
// 	GetMemory3(str,100);
// 	cout<<str<<endl;
// 	strcpy(str,"hello");
// 	cout<<str<<endl;
// 	delete [] str; 
// 	str=NULL;

// 	char* str=NULL;
// 	str=GetMemory4(100);
// 	strcpy(str,"hello");
// 	cout<<str<<endl;
// 	delete [] str; 
// 	str=NULL;

// 	char* str=NULL;
// 	str=GetMemory5();//GetMemory5()返回后str不再是NULL指针,但str的内容不是"hello world",而是垃圾信息,可以是乱码
// 	strcpy(str,"hello");
// 	cout<<str<<endl; 

	char* str=NULL;
	str=GetMemory6();//GetMemory6()返回的是一个"只读"的内存块
	cout<<str<<endl; //输出"hello world"
	strcpy(str,"hello");
	cout<<str<<endl; 
}
int _tmain(int argc, _TCHAR* argv[])
{
	test();
	return 0;
}