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?
You are not sending buffer
by reference (or as a pointer to vector<unsigned char>*) when calling
read_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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With