Re: How does "new" work in a loop?



"Matt" <matttelles@xxxxxxxxxxx> wrote:


So what is happening here? Is the memory being reused, or am I piling
up objects on the heap that will only go away when my program ends, or
am I creating a huge memory leak?

Unlikely that you are creating a memory leak. C# uses garbage
collection. When the object goes out of scope (in your case, the }
marked // for int i) the object is destroyed. The next time through
the loop, a new one is created.

It isn't freed immediately on every loop, or when it goes out of scope,
unless it's a value type (struct in C#). The GC kicks in on an as-needed
basis: memory pressure, repeated allocations, etc. That's one thing, and
is easy.

The other half of the story is resources. The GC isn't a resource
manager, so you shouldn't rely on it to manage things like file handles,
since it won't release them in a timely manner. That's why it's
important to use "using" with FileStream and other classes which
implement IDispose.

-- Barry

--
http://barrkel.blogspot.com/
.



Relevant Pages

  • Re: Confusion about Image object and PictureBox usage.
    ... I am not sure if I have a memory leak or not. ... >> scope, as with almost all objects in .NET. ... >> leak is coming from elsewhere, possibly in the code that is converting ... >> JPEG getting converted to a .NET bitmap? ...
    (microsoft.public.dotnet.framework.drawing)
  • Re: Memory leak in ruby code
    ... Even when it's out of scope, ... leaks in ruby code is still not very clear to me. ... I'd like to see if someone can point me to an example of memory leak ... Dont judge those who try and fail, judge those who fail to try.. ...
    (comp.lang.ruby)
  • Re: Psuedo-dynamic allocation?
    ... exist after the code that created them goes out of scope: ... Memory leak! ... home dot pacbell dot net slant earnur slant ...
    (comp.lang.cpp)
  • Re: How does "new" work in a loop?
    ... Unlikely that you are creating a memory leak. ... It isn't freed immediately on every loop, or when it goes out of scope, ... it will kick in when it makes ... The other half of the story is resources. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: char*
    ... goes out of scope, not that it is. ... would this cause a memory leak? ... So running foo() 1000 time would create 1000 string literal ... So the second time foo() is called the string literal constructed ...
    (comp.lang.c)