开发者

Dynamically allocated array inside std::list leads to memoy leaks

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 anyo开发者_运维问答ne 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.


Can't see any memory leak in your code...

You really should use RAII, and you wouldn't need to worry about it... and I would guess that std::vector could be a better choice here since you probably want continuous memory...

e.g.

typedef std::array<float, 3> vec3;
std::vector<vec3> vertices; 

for (int i = 0; i < 50000; i++)
{
    vec3 v = {13, 13, 13};
    vertices.push_back(v);
}  

vertices.clear();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜