1

please look at code below:

unsafe
{
   byte by = 1; // 1 byte 
   short sh = 1; // 2 bytes
   int it = 1; // 4 bytes
   double dou = 1; //8 bytes

   byte* byP = &by;
   short* shP = &sh;
   int* itP = ⁢
   double* douP = &dou;

   IntPtr add = (IntPtr)byP;
   IntPtr add2 = (IntPtr)shP;
   IntPtr add3 = (IntPtr)itP;
   IntPtr add4 = (IntPtr)douP;

   Console.WriteLine(Marshal.SizeOf(by) + " " + Marshal.SizeOf(sh) + " " + Marshal.SizeOf(it) + " " + Marshal.SizeOf(dou));
   Console.WriteLine(add.ToString() + " " + add2.ToString() + " " + add3.ToString() + " " + add4.ToString());

   //output:
   //1 2 4 8
   //--------------------------------------------------------------------
   //6943624 6943620 6943616 6943608
}

I cannot understand why for type like short or byte are reserved 4 bytes of memory in RAM if short needs 2 bytes and byte need only 1 byte right ? Could someone explain that to me please ?

Hadrian
  • 55
  • 1
  • 7
  • 7
    In short, memory alignment. It's done for performance reasons due to how a CPU cache works. See also [this great answer on the purpose of memory alignment](http://stackoverflow.com/a/381368/2873896). – Luke Briggs Jan 29 '17 at 17:09
  • 1
    Note only that this applies only to individual values. In a `byte[]`, every byte really does take up only 1 byte, not 4. – Jeroen Mostert Jan 30 '17 at 11:39

0 Answers0