CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: will this lead to memory leak? it shouldn't, should it?

  1. #1
    Join Date
    Jul 2007
    Posts
    43

    will this lead to memory leak? it shouldn't, should it?

    in my code i have something like

    Code:
    FileStream fs = new Filestream("file.txt", FileMode.Open);
    
    processFile(fs);
    |
    |
    |
    processFile(Filestream strm) {


    ...do something

    strm.close();
    }

    If I am closing the stream in the function processFile(), would that actually cause any memory leak? I mean strm and fs all point to the same objects..
    so techincally if i call strm.close(), the filestream itself would be closed, and strm will be destroyed on function call return since it is a local variable. And since fs refers to a closed stream, it should be picked up by the garbage collector right?

    please let me know.

    thnx

  2. #2
    Join Date
    Apr 2005
    Location
    Norway
    Posts
    3,934

    Re: will this lead to memory leak? it shouldn't, should it?

    and strm will be destroyed on function call return since it is a local variable.
    The variable/reference is 'destroyed'. But the object will exist until the fs reference runs out of scope. Then the garbage collector (when it kicks in) will pick up the object and dispose it.
    - petter

  3. #3
    Join Date
    Jul 2001
    Location
    Otaki, New Zealand
    Posts
    303

    Re: will this lead to memory leak? it shouldn't, should it?

    I believe it should get picked up by the garbage collection.

    Personally, IMHO, I believe responsibility for closing the FileStream lies within the scope of the object that created it. If used on a class basis, that class is responsible for opening and closing it. If used in a function scope, that function should both open and close it.

    .. and just to be sure, use 'using' instead

    Code:
    using (FileStream fs = new Filestream("file.txt", FileMode.Open))
    {
        processFile(fs);
    }
    Regards
    Alan

  4. #4
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    Re: will this lead to memory leak? it shouldn't, should it?

    But as far as I know, it will be closed, so the file's handle will be released, and the fs cannot be used any more, despite it still exists as .NET object.
    • Make it run.
    • Make it right.
    • Make it fast.

    Don't hesitate to rate my post.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)