Archived

This topic is now archived and is closed to further replies.

memory and loops...

This topic is 5751 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Just a quick question if I had:
  
for(;;)
{
   somefunc();
   int* var = new int;
   double num;
   // do more stuff

}
  
On each itteration of the loop would it be re-allocating memory and thereby using alot of memory, or would I have to add delete at the end and then have it re-allocated when it loops again or just declare all variables outside the loop? or does it only allocate once and then just uses them normally on each succesive loop?

Share this post


Link to post
Share on other sites
If you don''t delete the memory allocated with new (that''s dynamic memory), you have a memory leak. One that grows with each iteration of the loop (so, yes: it''ll keep reallocating memory, which also costs time and reduces performance). Statically allocated variables (in your case: the double) won''t be reallocated as such, but they are assigned a place on the stack (which shouldn''t grow over iterations of a loop, so that''s no problem). If the statically allocated variable has a constructor, that constructor is called, though. If possible, move variable declarations outside the loop.

Share this post


Link to post
Share on other sites
What?

If you allocate memory, free it. It''s that simple. If that means allocating it a few lines further up so that you don''t have to deallocate it once per loop iteration, so be it. Most major projects involve hundreds of files anyway, so if scrolling up a page is too much work for you, give up now!

[ MSVC Fixes | STL | SDL | Game AI | Sockets | C++ Faq Lite | Boost ]

Share this post


Link to post
Share on other sites