-2


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?

4

2 回答 2

2

您应该IDisposable为您的对象使用该模式。基本思想是这样的:

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;
    }
}

然后,您可以Dispose在确定不再需要它时立即调用您的对象,并且将释放非托管内存。

MyObject obj;
obj.Dispose();

或者,如果您忘记调用Dispose,则当垃圾收集器(通过终结器)收集对象时,将释放非托管资源。

于 2013-04-18T13:26:50.207 回答
0

我找到了解决我的问题的方法。问题的原因是内存碎片。在我的项目中,在项目的 c++ 部分中有很多大的(0.5 mb *(15-20 分配))对齐的内存分配,所以在分配和释放内存之后,不断地。有足够的内存用于未来的操作,但它被分成小部分。为了防止这种情况,我使用了内存池模式。而不是进行大量分配。我分配了一个大池并将其用于所有带有指针的数组。所以在c#部分操作如;
双 []k = 新双 [65536];
操作现在不会引起问题。

于 2013-04-19T18:42:05.590 回答