指针参数是如何传递内存的

如果函数的参数是一个指针,不要指望用该内存去申请动态内存

void GetMemory(char * p ,int num)

{

  p=(char*)malloc(sizeof(char)*num);

}

void Test(void)

{

  char* str=NULL;

 GetMemory(str,100);

  strcpy(str,"hello");

}


编译器总是要为函数的每个参数制作临时副本,指针参数p的副本是_p,编译器使_p=p.

在本例中,_p申请了新的内存,只是把_p所指的内存地址改变了,但是p丝毫未变。

事实上,每执行一次GetMemory就会泄露一块内存,没有用free释放内存.


void GetMemory2(char** p,int num)

{

  *p=(char*) malloc(sizeof(char)*num);

}

void Test2(void)

{

  char*  str=NULL;

 GetMemory2(&str,100);//注意参数是&str,不是str

 strcpy(str,"hello");

 cout<<str<<endl;

  free(str);

}


用函数返回值传递动态内存

char *  GetMemory3(int num)

{

    char* p=(char*) malloc(sizeof(char)*num):

   return p;

}


void Test3(void)

{

  char*  str=NULL;

  str=GetMemory3(100);

   strcpy(str,"hello");

  cout<<str<<endl;

  free(str);

}


强调不要用return 语句返回指向“栈内存”的指针,因为内存在函数结束时自动消亡

char * GetString(void)

{

  char p[]="hello world";

  return p;

}


void Test4(void)

{

  char*  str=NULL;

  str=GetString();

  cout<<str<<endl;

}

发现执行str=GetString语句后str不再是NULL指针,而是str的内容不是“hello world”而是垃圾


char* GetString2(void)

{

   char* p="hello world";

   return p;

}


void Test5(void)

{

    char* str=NULL;

     str=GetString2();

     cout<<str<<endl;

}


运行虽然不会出错,但是函数GetString2的设计概念却是错误的,因为GetString2内“hello world”是常量字符串,位于静态存储区,程序生命期内恒定不变。

无论什么时候调用GetString2,返回的始终是同一个只读的内存块。










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值