Memory problem - malloc, pointers and vector
Hi, I'm going to try to explain my problem... which is related to a bitmap painting program. I get a crash when already freed memory is getting used. It seems malloc is allocating the memory to the same location twice or something is going wrong with the pointers.
I have a std::vector<Layer> which is filled with layers. Each Layer class instance has a pointer to a memory buffer of pixels allocated using malloc. The vector is inside a class that is static and global.
When I delete a layer from the vector I do (pseudocode):
Layer layer = layers[index];
to save the layer (and the memory pointer it contains) to a place outside the vector and then I erase that Layer from the vector. I then send the saved layer to the undo system of the program. In the undo system the pixel buffer is freed when it goes out of scope.
The next time the program is run the layers are filled up again with new buffers using malloc. After that is complete it so happens that the destructor of the layer I sent to the undo system is called. It then deletes the same memory that is used by the new layer in the vector at the place where it was first deleted even though I allocated new buffers using malloc for the new layers.
Do you get it? It is kind of hard to explain...
Why isn't malloc allocating unique memory the second time?