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




Tony Sinclair wrote:
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?

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.

Matt

.



Relevant Pages

  • Re: return an int from a function
    ... The following code will generate a memory leak. ... int func{ ... //process the num, counting the loop ...
    (comp.lang.c)
  • Re: return an int from a function
    ... I would like to have a function to process an input integer and return the ... The following code will generate a memory leak. ... //process the num, counting the loop ... int result; ...
    (comp.lang.c)
  • Re: Fridays the thirteenth. (And a little puzzle.)
    ... -- compiler) is the usual method ... int febdays ... -- We're going to go round a loop dealing with each year in turn. ... -- other languages call) ...
    (uk.people.silversurfers)
  • Re: C code is not generating required results.
    ... int main ... the array by the size of an element. ... prevent the user of your program from entering more characters than ... want to loop. ...
    (comp.lang.c)
  • Re: long double versions of functions in gcc under Cygwin
    ... rather than the nearest enclosing one) and a decent exception ... them it doesn't seem like goto usage would be affected ... int typfun() ... Why use a for loop when it is just a while loop in disguise? ...
    (comp.lang.c)