Why do I have padding in the stack?

257 Views Asked by At

I was trying to understand how the stack (segment) works and thought that it will simply allocate each element (variable, byte, whatever I want to allocate) one after another. BUT after writing following code I noticed something strange.

var arr = stackalloc int[4];
int i = 3;

arr[4] = 9; // shouldn't this overwrite the int i?

When looking into memory I noticed that my integer is far away from my stack allocated pointer (in square you can see the memory of my allocated integer.)

enter image description here

QUESTION

  • Why isn't the memory of integer allocated right after my array?
  • What information does the line in the middle hold? (13 9a 3d 08 31 04 00 00)

NOTE

My integer is consistently "5 ints" away from my array, which means whenever I change my code to this:

var arr = stackalloc int[4];
int i = 3;

arr[9] = 9; // Notice the index 4 is changed to 9.

then my integer gets in fact overwritten.

0

There are 0 best solutions below