0

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.

  • So your assumption proved wrong. The stack layout is up to the Jitter and I don't think there are such fixed rules it has to obey as they would exclude any clever optimizations. – Klaus Gütter Mar 04 '21 at 06:34
  • @KlausGütter So you want to say that there are no predictable rules? But the "stack logic" was programmed by someone. Isn't there really any logic to it? Do the creators of C# randomly allocate memory? –  Mar 04 '21 at 06:37
  • This might be interesting to read: https://mattwarren.org/2017/05/08/Arrays-and-the-CLR-a-Very-Special-Relationship/ – Klaus Gütter Mar 04 '21 at 06:51
  • @KlausGütter Thank you for the link. Was interesting to read. I still have question why is it so unpredictable when I have consistently 5*32 byte padding between the array and integer? Maybe I missed something in the article that you provided. If so can you write that as an answer? (: –  Mar 04 '21 at 07:11
  • Why do you even care? This is an implementation detail of the Jitter. And if it is not specified, you cannot rely on it. – Klaus Gütter Mar 04 '21 at 09:07
  • 1
    @KlausGütter Knowing the tools I use is important for me. Why shouldn't I care? –  Mar 04 '21 at 09:42

0 Answers0