Pergunta


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?

Foi útil?

Solução

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).

Outras dicas

I found out a solution for my problem. Cause of problem is memory fregmentation. In my project there are lots of big (0.5 mb * (15-20 allocation)) aligned memory allocation in c++ part of project, so after allocating and freeing memories, continously. There is enough memory for future operations but it is splitted to small parts. To prevent this I used memory pool pattern. Instead of taking lots of allocation. I allocate one big pool and used it for all arrays with pointers. So in c# part operations such as;
double []k = new double[65536];
operations don't cause problem now.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top