0

I have experience in C and C++(languages without GC) but just recently using C# a lot. I have a question to which I think I got the answer but I want for someone to confirm me, or correct me(if I am wrong).

Say I have the following

int[,] g = new int[nx, ny];

very easy. This just separates memory for a 2D array of ints. After that I can use it, provided that I don't surpass nx or ny as limits of the array.

Now, suppose I want to do this several times but with different nx's and ny's everytime (how this new values are calculated is of no importance)

so I would do

int[,] g;

for(k=0;k<numberOfTimes;k++)
{
 //re-calculate nx and ny


 g = new int[nx, ny];

 //work with g


}

normally I would think that everytime I am separating memory for g, I am leaving leaked memory that could never be reached. Obviously I would have to "delete" this. But since C# has Garbage Collection, can I do the above with impunity??

In other words, is my code above safe enough?

any suggestion to better it?

KansaiRobot
  • 7,564
  • 11
  • 71
  • 150
  • It's fine how you're doing it. Just make sure that any non-local fields that contain a reference to that array (if any) are set to null or replaced with a reference to the new array. If you have, say, a static field that references an array, obviously the memory will be retained while that reference is still reachable. – Matthew Watson Feb 07 '17 at 09:10
  • Short answer: unless you are dealing with unmanaged resources or are allocating objects that are really big, you don't generally have to worry about memory leaks in C#. – Abion47 Feb 07 '17 at 09:11

1 Answers1

3

Your code is safe enough.

GC collects only those objects on the heap that have no references on the stack pointing to them. As in your scenario, a variable in the for loop scope gets another reference, the previous array loses all available references to it and thus gets collected in some time.

Also, there is no need to declare the variable in the outer scope as it is optimized later on during compile time. More about that : here

Community
  • 1
  • 1
Operatorius
  • 328
  • 2
  • 11