How many bytes of memory will be allocated in stack and in heap if we use a 64-bit processor?

Published on Author Code Father

answer of 44 bytes is probably a confusion referring to an array of 32 bit architecture.

In. Net (32 bit):

  • Every object contains 4 bytes for synchronization (lock (obj)).
  • Every object contains 4 bytes of its type token.
  • Every array contains 4 bytes of its length.

The pointer is 8 bytes as you said.

This with the 24 bytes of the array itself gives you 44 bytes.


However, this is the header layout for 32 bit.

As you can see, the memory layout of the following code:

var p = new Point[3];
p[0] = new Point { x = 1, y = 2 };
p[1] = new Point { x = 3, y = 4 };
p[2] = new Point { x = 5, y = 6 };

var p2 = new Point[3];
p2[0] = new Point { x = 8, y = 8 };
p2[1] = new Point { x = 8, y = 8 };
p2[2] = new Point { x = 8, y = 8 };

Will be:

Memory layout

You can see the number values in the memory layout as well.


In 64 bit, each field of the header with its takes 8 byte so that the header length is 24 bytes therefore the length of the entire array is 48 bytes and with the variable pointing to the array: 56 bytes.

64 bit architecture memory layout:

64 bit memory layout


Notes:

  • If your array wasn’t rounded up to an 8 byte multiple alignment would take place, but it is so alignment is not required. Example (two 1 sized int arrays):

    Alignment

  • Even though the length field of the header is 8 bytes in 64 bit, it’s larger than the maximum array size .NET allows therefore only 4 may be used.

Keep in mind that this is an implementation detail and it might change between implementations/versions of the CLR.

Comments

comments

Categories C#