函数不能传递动态内存

链接:解释好像有点问题

1、函数给传入的指针申请动态内存

1)函数参数为一级指针申请内存,无返回值:错误

(1)在GetMemory中。形参p实际上是str的一个副本。在本例中,p申请了新的内存,p的值改变了,即p指向的内存地址改变了,但是str丝毫未变。因为函数GetMemory没有返回值,因此str并不指向p所申请的那段内存。事实上,每执行一次GetMemory函数就会申请一块内存,但申请的内存一直被独占,最终造成内存泄漏。

#include <iostream>
using namespace std;
void GetMemory(char* p, int num)
{
    p = (char*)malloc(sizeof(char*)num);
};
 
int main()
{
    char* str = NULL;
    GetMemory(str, 100);
    strcpy(str, "hello");
    return 0;
}

2)函数参数为二级指针,即指向指针的指针:正确

#include <iostream>
using namespace std;
void GetMemory(char** p, int num)
{
    *p = (char*)malloc(sizeof(char*)num);
};
 
int main()
{
    char* str = NULL;
    GetMemory(&str, 100);
    strcpy(str, "hello");
    cout << *str << endl;
    cout << str << endl;
    cout << &str << endl;
    return 0;
}

3)函数返回形参指针

#include <iostream>
using namespace std;
char* GetMemory(char* p, int num)
{
    p = (char*)malloc(sizeof((char*)num));
    return p;
};
 
int main()
{
    char* str = NULL;
    str = GetMemory(str, 100);
    strcpy(str, "hello");
 
    cout << *str << endl;
    cout << str << endl;
    cout << &str << endl;
 
    return 0;
}

2、主要是避免在函数体中为传入的指针直接申请内存,因为传入的实参会发生复制,而函数体是对复制的形参进行操作,并没有直接对实参进行操作;

posted @ 2019-04-17 23:07  kuaqi  阅读(330)  评论(0编辑  收藏  举报