返回動態內存--malloc

返回動態內存--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/



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章