2012-11-08 6 views
2

내가 대신 그것은에서 OutOfMemory 예외가 발생, Marshal.AllocHGlobal을 실험하고 있는데이 코드는 성공하지 않을 것이라고 수수께끼 발견 :왜 이것이 OutOfMemory를 던집니까?

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

왜 AllocHGlobal 호출이 성공하면 그것이에서 OutOfMemory을 얻을 것인가?

+0

분할의 원인이되는 파일을 읽고는'Marshall.Copy'이 그것을하고있어 제외 또는'File.ReadAllBytes'을 던지고 있는지 확인해야한다. 나는 후자를 걸 겠어. – MusiGenesis

+0

2MB ~ 800MB RAM이 없다는 것을 의미하지 않습니까? – Jasper

답변

6

원인 File.ReadAllBytes(fileName)는 두 개로 줄 추가 ~ 800메가바이트

+1

댕 ... 네 말이 맞다. –

+0

나는 믿기 때문에 10 분간 기다려야한다. –

+1

+1. 아마 관심의 - http://stackoverflow.com/questions/4742016/using-vs2010-profiler-for-memory-measurement. 또한 try/catch 문을 블록 주위에 추가하는 것이 좋습니다. 이렇게 큰 개체를 메모리에로드 할 때'using' 문을 사용하여 메모리에 저장하면 항상 삭제됩니다. http://msdn.microsoft.com/ en-us/library/yh598w02 (v = vs80) .aspx –

관련 문제