pixel
pixel

Reputation: 10547

Is there a memory leak in this code

If I have a class with constructor that takes an array like this:

    public struct MyStruct{
    Car car;
    Boolean processed;
}

public class MyClass{
    private MyStruct[] mCarStructs;

    public MyClass(Car[] cars)
    {
        //So the only reason I pass Car[] in is to use it to
        //populate my array of structs
        mCarStructs = new MyStruct[cars.Length];

        for (int i = 0; i < cars.Length; i++)
        {
            myCarStructs[i].car = cars[i];
            myCarStructs[i].processed = false;
        }
    }

    public void processCar(...)
    {
        if (DoProcess(myCarStructs[i].car))
        {
            myCarStructs[i].processed = true;
        }
    }

    ...
    ...
}

My understanding is that arrays are passed in by default as a reference. So, I dont think this is a leak and the reference passed in constructor will be nulled once constructor code completes.

So, there is no leak. Is this correct?

Thanks,

Upvotes: 0

Views: 54

Answers (1)

Servy
Servy

Reputation: 203823

Arrays are not passed by reference, arrays are references. The reference to the array is passed by value.

As for memory leaks, the Garbage Collector is going to clean up all managed objects as soon as there are no longer any references to those objects; you don't need to worry about explicit memory management except in those cases where you're dealing with unmanaged memory (which you're not doing here).

Upvotes: 4

Related Questions