Invalid pointer - why?

Not very experienced with C ++, I have 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 buffer pointer in read_image() . At runtime, I get this when I try to free the heap:

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

What is wrong with my approach?

+4
source share
3 answers

You do not send buffer by reference (or as a pointer to vector<unsigned char>*) when calling read_image`, so the function cannot distribute the update outside the function (i.e. 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); } 

Now we pass the link as a parameter to read_image , and the original variable will be updated with the value returned with new vector<...> (...) .


If you are a pointer fanatic, this is also true:

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

In the above example, we give read_image the address of the pointer itself, and inside we can dereference that pointer to a pointer to set the value that the original pointer points to.

Sorry for the wording, I'm very tired of being honest.


Frequently asked questions regarding the use of links.

+11
source
 void read_image(vector<unsigned char>* & buffer) { // passed by reference 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; } 
+2
source

I think you want to create a buffer that can contain more than one image, otherwise I don’t know why you need a vector.

if my assumption about the correctness of your requirement is correct, you should do something like this -

 void read_image(vector<unsigned char*>& buffer,int size) { char* p = new char[size]; buffer.push_back(p); } void process_image_buffer(char* image_buffer) { // Do something with image_buffer } int main(int argc, char ** argv) { vector<unsigned char*> buffer; for all images // calculate the unknown size at runtime here egby taking input from user read_image(buffer,size); // Do Image Processing // process each image buffer in a for loop for all images (i < buffer.size()) process_image_buffer(buffer[i]); // Free all at end for all images (i < buffer.size()) delete[] buffer[i]; return 0; } 
+2
source

Source: https://habr.com/ru/post/1386514/


All Articles