How does "new" work in a loop?
- From: Tony Sinclair <no@xxxxxxxx>
- Date: Thu, 06 Jul 2006 13:37:47 -0700
I'm just learning C#. I'm writing a program (using Visual C# 2005 on
WinXP) to combine several files into one (HKSplit is a popular
freeware program that does this, but it requires all input and output
to be within one directory, and I want to be able to combine files
from different directories into another directory of my choice).
My program seems to work fine, but I'm wondering about this loop:
for (int i = 0; i < numFiles; i++)
{
// read next input file
FileStream fs = new FileStream(fileNames[i],
FileMode.Open, FileAccess.Read, FileShare.Read);
Byte[] inputBuffer = new Byte[fs.Length];
fs.Read(inputBuffer, 0, (int)fs.Length);
fs.Close();
//append to output stream previously opened as fsOut
fsOut.Write(inputBuffer, 0, (int) inputBuffer.Length);
progBar.Value++;
} // for int i
As you can see, the objects fs and inputBuffer are both created as
"new" each time through the loop, which could be many times. I didn't
think this would work; I just tried it to see what kind of error
message I would get, and I was surprised when it ran. Every test run
has produced perfect results.
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?
I can see that fs might go away after fs.Close(), but I don't
understand why I'm allowed to recreate the byte array over and over,
without ever disposing of it. I have verifed with the debugger that
the array has a different size each time the input file size changes,
so it really is being reallocated each time through the loop, rather
than just being reused. I've tried to find explanations of how "new"
works in a loop, but I haven't been able to so far. Any help,
including pointers to the VS docs or a popular book on C#, would be
appreciated.
.
- Follow-Ups:
- Re: How does "new" work in a loop?
- From: Ian Semmel
- Re: How does "new" work in a loop?
- From: Tony Sinclair
- Re: How does "new" work in a loop?
- From: Matt
- Re: How does "new" work in a loop?
- From: John J. Hughes II
- Re: How does "new" work in a loop?
- From: Peter Rilling
- Re: How does "new" work in a loop?
- Prev by Date: ListView doesn't show images in release (LargeIcon mode)
- Next by Date: Re: Casting up to inheriting class from base?
- Previous by thread: ListView doesn't show images in release (LargeIcon mode)
- Next by thread: Re: How does "new" work in a loop?
- Index(es):
Relevant Pages
|
Loading