#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
//1,调用GetMemory( str )后, str并未产生变化,依然是NULL.只是改变的str的一个拷贝的内存的变化
//2,strcpy( str, "hello world" );程序运行到这将产生错误。
//3,new的时候有可能内存出错,应该在*p = (char *) malloc( num ); 后判断内存是否申请成功,应加上:
/*if ( *p == NULL )
{
...//进行申请内存失败处理
}*/
//4,动态创建的内存没释放。
//要记得使用指针变量时,每次分配空间后要判断是否分配成功。而且在主函数中使用之后记得释放内存,并置空
/*内存空间状态:首先申请了四个字节的栈空间,存放str指针,此时str的值为0,
存放str的这块内存的地址值为0x0012ff7c。调用函数 GetMemory,指针P入栈,
也分配了四个字节的栈空间,P被赋str的值即此时P的值也为0,存放指针P的内存地址是0x0012ff2c。
然后将新开辟的100个字节的内存空间地址赋给P,此时P的值为0x00372b70
。函数调用结束时str的值仍为0,str并没有得到那块100个字节的内存空间地址值!*/
char* GetMemory1()
{
char* p = "hello1";
return p;
}
void Test1()//可以正常输出
{
char *str = NULL;
str = GetMemory1();
cout<<str<<endl;
}
void GetMemory2(char * p)
{
//cout<<p<<endl;空指针没有指向任何地址
p = (char*)malloc(100);
if(p==NULL)
{
cout<<"申请内存失败"<<endl;
}
cout<<*p<<endl;
}
void Test2()//不可以
{
char * str = NULL;
//cout<<str<<endl;这句话是不正确的NULL指针不知想任何地方
GetMemory2(str);
cout<<*str<<endl;
strcpy(str,"hello2");
cout<<str<<endl;
}
void GetMemory3(char** p,int num)//可以正常运行
{
*p = (char*)malloc(num);
//要记得使用指针变量时,每次分配空间后要判断是否分配成功。而且在主函数中使用之后记得释放内存,并置空
if(*p==NULL)
{
cout<<"申请内存失败"<<endl;
}
}
void Test3()
{
char* str = NULL;
GetMemory3(&str ,100);
if(str==NULL)
{
cout<<"申请内存失败"<<endl;
}
strcpy(str,"hello3");
cout<<str<<endl;
free(str);//释放内存
str = NULL;//置空
}
void Test4()
{
char* str = (char*)malloc(100);
strcpy(str,"hello4");
if(str==NULL)
{
cout<<"申请内存失败"<<endl;
}
free(str);
cout<<str<<endl;//输出乱码 因为成为野指针 指向不定内存
str =NULL;//置空
}
char* GetMemory5(char *& p,int num)
{
p = (char*)malloc(num);
if(p == NULL)
{
cout<<"内存分配"<<endl;
}
return p;
}
void Test5()
{
char* str = NULL;
str = GetMemory5(str,100);
if(str== NULL)
{
cout<<"内存分配失败"<<endl;
}
strcpy(str,"hello5");
cout<<str<<endl;
free(str);
str=NULL;
}
int main()
{
//Test1();
//Test2();
//Test3();
//Test4();
Test5();
return 0;
}