简体   繁体   中英

C# Out of Memory exception while combining byte array

I am getting out of memory exception while combing byte array of size 10MB until the main array of 500MB

The method I am using to combine byte array is:

private byte[] Combine(byte[] mainarray, byte[] newarray)
{
    byte[] c = new byte[mainarray.Length + newarray.Length];
    System.Buffer.BlockCopy(mainarray, 0, c, 0, mainarray.Length);
    System.Buffer.BlockCopy(newarray, 0, c, mainarray.Length, newarray.Length);
    newarray = null;
    mainarray = null;
    return c;
}

Any idea where I am going wrong?

In a 32 bit application, it is likely that you get an OutOfMemoryException, because you have (if I understand that correctly)

  • a source array of 10 MB
  • another source array of 490 MB
  • the destination array of 500 MB

Since arrays need to be contiguous in memory, .NET must be able to allocate a single large block of 500 MB, which is quite unlikely.

I'd like to demonstrate this in the debugger, but this issue currently prevents me from doing it. The command in WinDbg is !address -summary and you need to look for the largest free block.

Basically it may look like this:

--- Usage Summary ---------------- RgnCount ----------- Total Size -------- %ofBusy %ofTotal
<unclassified>                         6007          57a86000 (   1.370 Gb)  85.37%   68.48%
Free                                    268          19519000 ( 405.098 Mb)           19.78%

...

--- Largest Region by Usage ----------- Base Address -------- Region Size ----------
<unclassified>                               66f0000           c041000 ( 192.254 Mb)
Free                                        71c97000           4109000 (  65.035 Mb)

which means, there is 405 MB free, but only 65 MB in a single block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM