I'm screwing around with the Visual Studio 2013 C++ compiler (what I'm doing is not really important or interesting at all) and I'm running across some very odd behavior. Right now I have the code:
void fun(void)
{
int *ebp = (int *)(&ebp + 1);
}
Which should give me a pointer to ebp using Visual Studio's stack semantics. NOTE: I have set Basic Runtime Checks to "Default" and I have disabled security checks. When I look at the memory when debugging in Visual Studio I see:
0x009BFBFC 41 03 81 51 fe ff ff ff 44 fc 9b 00
Where 0x009BFBFC
is the address of ebp. Note that there is a random -2 in the location immediately preceding ebp (0xfffffffe
). Also note that the saved ebp is right after this -2 (0x009bfc44
). "Okay" I say, "I'll just add 2 instead!" I now have this code:
void fun(void)
{
int *ebp = (int *)(&ebp + 2);
}
And when I run it and look at the memory, this time I see:
0x0032FCD8 fe ff ff ff 1c fd 32 00 5e 3c 39 00
Again, 0x0032FCD8
is the address of ebp. What madness is this! The random extra space is now gone giving me a pointer to the return address instead!
Is this deliberate? I can't see any reason why the Visual Studio compiler would intentionally prevent me from accessing the base pointer from code, but then again I can't see why the compiler would behave so oddly when I change a two to a one. For those curious, I looked at the disassembly and the first example does allocate 4 more bytes than the second for no apparent reason (it's not used anywhere). If anyone has any insight, that would be awesome; this is kind of irritating that it would do this.
User contributions licensed under CC BY-SA 3.0