0

Even though there are similar problems discussed in the forum (here, here, here), I could not find the answer for this problem.

I have a simple test code to allocate memory and release it by using unmanaged code inside C#. My observation is that, whenever I compile this code in debug mode, it is allocating memory and I can see it in task manager(and even I can cause a freeze by allocating memory until 100%). However, whenever I compile it in release mode, it does not allocate memory. To do that, I need to marshall copy the pointer to a byte array and it caused 200MB memory usage for 100MB allocation (100MB + N x 100MB, where N is the number of allocation).

First question is, why I cannot allocate (or why it is deallocating too fast) in release mode build?

Second question is, if i try to allocate memory block of 1GB at once, it is not always allocating 1GB (or deallocating some of it too fast), so whenever I count the allocated memory, it exceeds my maximum available RAM limit. What can be the reason for it?

C# button on click calling

var pointerList = new List<IntPtr>();
int mb = 100 * 1024 * 1024;
IntPtr ptr = InteropClass.Allocate(mb);

#region For Release
byte[] by = new byte[mb];
Marshal.Copy(ptr, by, 0, mb);
#endregion

pointerList.Add(ptr);

C# Interop Callings:

class InteropClass{
[DllImport("CustomInterop.dll")]
public static IntPtr AllocateMemory(int mb);
[DllImport("CustomInterop.dll")]
public static void ReleaseMemory(IntPtr ptr);
}

C++ Headers:

extern "C" __declspec(dllexport) void * AllocateMemory(int mb);
extern "C" __declspec(dllexport) void  ReleaseMemory(void* ptr);

C++ Content:

void *  AllocateMemory(int mb) {
    unsigned char* buffer = (unsigned char*)malloc(mb);
    return buffer;
}

void ReleaseMemory(void* ptr) {
    free(ptr);
}
Community
  • 1
  • 1
Deniz Beker
  • 1,984
  • 1
  • 18
  • 22
  • "*it is allocating memory and I can see it in task manage*" -- Don't use task manager to determine whether memory is allocated or not. It is not a valid tool to use, as it is the compiler's heap manager that parcels out the memory. The C++ heap manager does not naively allocate memory from the OS and returns it again when `delete` or `free` is called. – PaulMcKenzie Mar 04 '16 at 01:59
  • I should say that task manager is valid *if* your program actually calls OS functions to allocate and deallocate memory (i.e. `HeapAlloc`, `GlobalAlloc`, `GlobalFree`, etc.). But C and C++ runtime calls such as `new`, `malloc`, etc. cannot be tracked accurately by Task Manager. – PaulMcKenzie Mar 04 '16 at 02:05
  • I agree that it cannot be tracked accurately by Task Manager. That's why, in each case, I tried to allocate until the system freezes or throws outofmemory exception. However, PC did not freeze neither throw an exception if I did not see any memory increase in Task Manager. – Deniz Beker Mar 04 '16 at 02:12

0 Answers0