John Smith John Smith - 3 months ago 13
C# Question

How many bytes get allocated for 3 Point structs on a 64-bit processor?

There is a question


Given struct Point {int x; int y;} var p = new Point[3], how many bytes of memory will be allocated in stack and in heap if we use a 64-bit processor?


The correct answer is 44. Can somebody explain how did this number appear?

As far as I understand,
p
will occupy 8 bytes in stack for
x64
.

And we have two values of
Int32
per structure, thus
p.Length * sizeof(Point)

3 * 8 = 24 bytes in heap for an array.

That will be 32 bytes. What is the rest 12 bytes for in this case?

Answer

In .Net:

  • 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 (even for 64 bit).

The pointer is 8 bytes as you said.

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


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.

Comments