Search code examples
c#memory-managementmanaged-c++

C# cannot take new memory



I am working a c# - c++ (manage) mix project and we realize there are memory leaks in our project, so I searched and found out, destructor of c++ part never called so I wrote a piece of code to free memories. Now I can see program growing slower in memory (there are more memory leaks), but the problem is, in c# part program start to crash because of "out of memory exception". In operation such as

double []k = new double[65536];

Memory usage of program normally seems 400-500mb but it crashed.
OS : win server 2003
Memory : 4 GB
OS should let program to grow nearly 1200 mb but after I wrote the free memory part it start to crash 400-500mb.
I called this c++ func from the c# part to free memories

freeMemories()
{
   if(!mIsAlreadyFreedMemory)
   {
      mIsalreadyFreedMemory = true;
      _aligned_free(pointerA);
      _aligned_free(pointerB);
       ....
    }
}

Why it cannot take new memory, Program can not take the released memory again?


Solution

  • You should use the IDisposable pattern for your objects. The basic idea is this:

    public class MyObject : IDisposable
    {
        // Some unmanaged resource:
        UnmanagedResource unmanaged;
    
        // Finalizer:
        ~MyObject
        {
            DisposeUnmanaged();
        }
    
        public void Dispose()
        {
            DisposeManaged();
            DisposeUnmanaged();
            GC.SuppressFinalize(this);
        }
    
        protected virtual DisposeManaged()
        {
            // Dispose _managed_ resources here.
        }
    
        protected virtual DisposeUnmanaged()
        {
            // Dispose _unmanaged_ resources here.
            this.unmanaged.FreeMe();
            this.unmanaged = null;
        }
    }
    

    Then you can call Dispose on your object as soon as you're sure it is no longer needed, and the unmanaged memory will be freed.

    MyObject obj;
    obj.Dispose();
    

    Or, if you forget to call Dispose, the unmanaged resources will be freed when the object is collected by the garbage collector (through the finalizer).