I am experimenting with Marshal.AllocHGlobal and found puzzling that this code would not succeed, instead it throws an OutOfMemory exception:
namespace HAlloc
{
using System;
using System.IO;
using System.Runtime.InteropServices;
class Program
{
static void Main(string[] args)
{
// large file ~ 800MB
string fileName = @"largefile.bin";
FileInfo fileInfo = new FileInfo(fileName);
// allocation succeeds
IntPtr p = Marshal.AllocHGlobal((int)fileInfo.Length);
// OutOfMemory exception thrown here:
Marshal.Copy(File.ReadAllBytes(fileName), 0, p, (int)fileInfo.Length);
Marshal.FreeHGlobal(p);
}
}
}
Why would it get an OutOfMemory when the AllocHGlobal call succeeded?
Cause
File.ReadAllBytes(fileName)also has to read the file which causes extra ~800 MB