返回动态内存--malloc

来源:互联网 发布:java httputils 编辑:程序博客网 时间:2024/05/17 22:28

返回动态内存--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;
}

 

文章转自:http://zeorro.blog.163.com/blog/static/18689205820122463927802/