c++指针值传递的坑

错误做法:

void GetMemory (char *p) {
    p = (char *)malloc(1000);
}
void Test(void){
    char *str =NULL;
    GetMemory(&str);
    strcpy(str,"hello world");
    for (int i =0; i < strlen(str);i++){
        qDebug()<<str[i];
    }
    free(str);
}

上面代码: 

void GetMemory (char **p) {
    *p = (char *)malloc(1000);
}   P只是 str的一个拷贝值, p开辟了空间,但是str的值还是原来的空值, p在函数运行完就释放了,str这里没有内存空间;

函数的参数会产生一个临时变量,指针也是变量,所以这里指针是值传递,改变P开辟了空间而str没有得到改变;

正确做法:

void GetMemory (char **p) {
    *p = (char *)malloc(1000);
}
void Test(void){
    char *str =NULL;
    GetMemory(&str);
    strcpy(str,"hello world");
    for (int i =0; i < strlen(str);i++){
        qDebug()<<str[i];
    }
    free(str);
}

做个int类型的代码:

void test01(int *p){
    p = new int(10);
    qDebug()<<p <<"  "<<*p;
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    int *c = nullptr;
    //*c = 10;空值c,非法解引用 会导致程序崩溃  需要开辟空间才能解引用 c = new int(10)
    qDebug()<<c;
    qDebug()<<"-------------";
    test01(c);
    qDebug()<<"-------------";
    qDebug()<<c;

    delete c;
    return a.exec();
}

输出结果:

0x0
-------------
0x17f8f0c2d60    10
-------------
0x0

可以看到 实践结果 c 拿不到函数来new的p 反而造成内存泄露
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值