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