无效的指针-为什么? [英] Invalid pointer - why?

查看:103
本文介绍了无效的指针-为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太了解C ++,我了解以下内容:

Not very experienced with C++, I've got the following:

void read_image(vector<unsigned char>* buffer) {
    buffer = new vector<unsigned char>(2048);
}   

int main(int argc, char ** argv) {
    vector< unsigned char > *buffer;

    read_image(buffer);

    delete buffer; // gives invalid pointer at run-time

    return 0;
}

这只是代码的相关部分,基本上我想在read_image()中初始化指针buffer.在运行时,尝试释放堆时出现此错误:

This is only the relevant part of the code, basically I want to initialize the pointer buffer in read_image(). At run-time I'm getting this when trying to free up the heap:

*** glibc detected *** ./main: free(): invalid pointer: 0x00007fff0648556c ***

我的方法有什么问题?

推荐答案

您不是通过引用发送buffer(或作为指向vector<unsigned char>*) when calling read_image`的指针,因此该函数无法将更新传播到外部函数(即调用方).

You are not sending buffer by reference (or as a pointer to vector<unsigned char>*) when callingread_image`, therefor the function is unable to propagate the update to outside of the function (ie. the caller).

对功能的这种修改将产生您所希望的:

This modification of your function will result in what you wish:

void read_image(vector<unsigned char>*& buffer) {
    buffer = new vector<unsigned char>(2048);
}   

我们现在将引用作为参数传递给read_image,原始变量将使用new vector<...> (...)返回的值进行更新.

We are now passing a reference as a parameter to read_image, and the original variable will be updated with the value returned from new vector<...> (...).

如果您是指针狂热者,这也有效:

void read_image (vector<unsigned char>** buffer) {
    *buffer = new vector<unsigned char>(2048);
}  

...

read_image (&buffer);

在上面,我们给read_image指针本身的地址,并且在内部我们可以将该指针取消引用到指针,以设置原始指针指向的值.

In the above we are giving read_image the address of the pointer itself, and inside we can dereference this pointer to pointer to set the value pointed to by the original pointer.

对不起,老实说,我很累.

Excuse the wording, I'm quite tired to be honest.

有关引用使用的常见问题.

FAQ regarding the use of references.

这篇关于无效的指针-为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆