I wanted to try pointer arithmetic in c#. I have used an asp.net web app, expecting that it wouldn’t matter if it was this or a console app.
here is what I tried:
public class memorytest
{
public class Sample
{
public int A;
public int B;
public int C;
public int D;
}
public static unsafe void Main()
{
Sample s = new Sample {A = 1, B = 2, C = 3, D = 4};
int a = 1;
int b = 2;
int* pA = &a;
int* pB = &b;
Debug.WriteLine("{0:x16}",* pB);
Debug.WriteLine("{0:x16}",*(pB - 1));
Debug.WriteLine(*pA);
Debug.WriteLine("{0:x16}",*(pB - 2));
}
}
The result was like this:
0000000000000002,
0000000004b5ca00,
1,
0000000004b5c9fc,
I was obviously expecting the second one to be the number 1. Does anybody understand this?
First off, if you want to learn how the stack is laid out, it seems like it would be a lot easier to start the debugger and look at the stack in the debugger.
Assuming that for some reason you want to keep on writing programs to examine their own stack state: you stopped experimenting too early. The program you should have written is:
and then you would have gotten the output
and you would have learned that stacks grow in the opposite direction that you think they do. In many architectures pushing something onto the stack decreases the stack pointer.
Of course, as others have pointed out, we make no guarantees whatsoever as to how stuff is laid out on the stack, or even if stuff goes onto the stack in the first place; local variables may be placed on the heap in some situations, and local variables whose addresses are never taken may be enregistered. For example, what happens if you don’t take the address of “a”? Does it still end up on the stack? Maybe not!