The following code leads to a memory leakage:
std::list<float*> vertices;
float* v;
for (int i = 0; i < 50000; i++){
v = new float[3];
v[0] = v[1] = v[2] = 13;
vertices.push_back(v);
}
std::list<float*>::iterator curr;
for(curr = vertices.begin(); curr != vertices.end(); curr++) {
delete[] *curr;
}
vertices.clear();
I have no idea why it is happening, but I guess it is connected to some anomaly of std::list.
The weirder part is that if I run the code more than once consequentially, the amount of leaked memory does not change. Can it be that I miss something really basic?
Can anyone suggest a reason for this? Can I solve this with only changing destruction part of the code?
More info:
This is an mfc application. The code is executed on a button press. Before I press the button I see 15mb in the task manager. After I press the button I see 40mb. The button does nothing but executing this code.
You are mis-interpreting your results. The “leak” you are seeing is not actually a leak, but pre-allocation, which is basically where the CRT or STL keeps around allocated memory incase you need it again for faster allocation time.
Moreover, you should really, really use self-releasing pointers. They’re guaranteed never to leak memory, if they’re used properly, and there’s a wealth of well-written smart pointers in Boost or a new compiler’s Standard library.
Edit: Task manager is NOT a reliable way to measure allocations/deallocations/etc. This doesn’t even allocate 25MB.
More edit: You wouldn’t even need to check if you used proper RAII pointers instead of raw pointers.