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

Tech-Archive recommends: Speed Up your PC by fixing your registry




Barry Kelly wrote:
"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.

Yes, I know this. The OP was a C++ programmer, I was giving it to him
in C++ context. GC is deterministic, it will kick in when it makes
sense
to kick in.


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.

True and a good point. I was just explaining why it wasn't a memory
leak,
but your explanation is better for this purpose.

Thanks
Matt

.



Relevant Pages

  • Re: leaks in GC?
    ... the small example is the result of tracking down a memory leak in ... Took me ages to realize that the reason is the simple .NET ContextMenu, ... the GC won't kick in. ...
    (microsoft.public.dotnet.languages.csharp)
  • 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, ... The other half of the story is resources. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Looping-related Memory Leak
    ... memory leak / balloon for reasons I cannot figure out. ... end of the loop. ... only local variables were used in the cached object's methods. ... Here the alleged "memory leak" is clearly the cache, ...
    (comp.lang.python)
  • Re: Looping-related Memory Leak
    ... memory leak / balloon for reasons I cannot figure out. ... end of the loop. ... reference count never reaches zero, and they remain alive until the ... the generational collector doesn't break cycles that involve ...
    (comp.lang.python)
  • Re: How does "new" work in a loop?
    ... freeware program that does this, but it requires all input and output ... My program seems to work fine, but I'm wondering about this loop: ... fsOut.Write(inputBuffer, 0, (int) inputBuffer.Length); ... Unlikely that you are creating a memory leak. ...
    (microsoft.public.dotnet.languages.csharp)