Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid pointer - why?

Tags:

c++

pointers

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;
}

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 ***

What's wrong with my approach?

like image 737
rdoubleui Avatar asked Dec 15 '11 13:12

rdoubleui


Video Answer


1 Answers

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);
}   

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<...> (...).


If you are a pointer fanatic this is also valid:

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

...

read_image (&buffer);

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.

  • parashift.com/c++-faq-lite/ - [8] References
like image 106
Filip Roséen - refp Avatar answered Nov 02 '22 23:11

Filip Roséen - refp