GetMemory()

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值