返回动态内存--malloc (转)

#include <stdio.h>
#include <stdlib.h>
void getmemory(char *p)
{
    p=(char*)malloc(100);
    strcpy(p,"hello world");
}
 
int main()
{
    char *str =  NULL;
    getmemory(str);
    prinrf("%s\n",str);
    free(str);
    return 0;
}

    此段代码有错,getmemory(str)中参数问题。编译器会为每个函数的参数都复制一份临时副本,指针参数 p 的副本在C中是_p,并且对_p赋值为p ,即 _p = p 。如果在getmemory函数体内修改了 _p,则导致参数 p 的内容做相应的修改。这就是指针可用作输出参数的原因。

     但此处中getmemory函数的 _p 申请了新内存,此时 _p 所指的内存地址改变了,但是 p 没变。所以每次调用getmemory都会造成内存泄露。

     形参p的域只在函数里有效,p一开始指向你想要的地址,但是当你重新分配内存的时候p指向了新的地址,当你返回函数的时候原来的地址还是空的。

     要在函数里返回内存有两种办法,一种是指针的指针 **p ,用这个指针指向一个需要分配内存的值。另外一种方法更简单,你在函数里创造一个指针然后 return他就可以了。

 

正确代码:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
using namespace std;
 
char * getmm(int mm)
{
   char *p=(char *)malloc(sizeof(char) * mm);
   if(p!=NULL)
       strcpy(p,"hello world");
return p;
}
 
void getm(char **p,int mm)
{
   *p=(char *)malloc(sizeof(char) * mm);
   if(*p !=NULL)
       strcpy(*p,"hello world");
}
 
int main(void)
{
   char *str = NULL;
   str = getmm(100);
    printf("%s\n",str);
    if(str!=NULL)
       free(str);
   cout << endl;
   
   char *ps = NULL;
   getm(&ps,100);
   cout << "ps=" << ps <<endl;
   free(ps);
   
   system("pause");
   return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值