开发者

Explain the strange assembly of empty C `main` function by Visual C++ compiler

开发者 https://www.devze.com 2023-01-09 15:33 出处:网络
I just noticed some strange assembly language code of empty main method. //filename: main.c void main()

I just noticed some strange assembly language code of empty main method.

//filename: main.c
void main()
{

}

disassembly:

push        ebp  
mov         ebp,esp  
sub         esp,0C0h; why on the earth is it reserving 192 bytes?  
push        ebx  
push        esi  
push        edi  ; good compiler. Its saving ebx, esi & edi values.
lea         edi,[ebp-0C0h]  ; line 1
mov         ecx,30h  ; line 2
mov         eax,0CCCCCCCCh  ; line 3
rep stos    dword ptr es:[edi]  ; line 4


xor         eax,eax  ; returning value 0. Code following this line is explanatory.
pop         edi  ; restoring the original states of edi,esi & ebx
pop         esi  
pop         ebx  
mov         esp,ebp  
pop         ebp  
ret   
  1. why on the earth 开发者_C百科is it reserving 192 bytes for function where there aren't any variables
  2. whats up with the four lines: line 1, line 2, line 3, line 4? what is it trying to do & WHY?


Greg already explained how the compiler generates code to diagnose uninitialized local variables, enabled by the /RTCu compile option. The 0xcccccccc value was chosen to be distinctive and easily recognized in the debugger. And to ensure the program bombs when an uninitialized pointer is dereferenced. And to ensure it terminates the program when it is executed as code. 0xcc is pretty ideal to do all of these jobs well, it is the instruction opcode for INT3.

The mysterious 192 bytes that are allocated in the stack frame are there to support the Edit + Continue feature, /ZI compile option. It allows you to edit the code while a breakpoint is active. And add local variables to a function those 192 bytes are available to provide the space for those added locals. Exceeding that space will make the IDE force you to rebuild your program.

Btw: this can cause a problem if you use recursion in your code. The debug build will bomb with this site's name a lot quicker. Not normally much of an issue, you debug with practical dataset sizes.


The four code lines you've indicated are the debug build clearing out the local variable space with the "clear" special value (0xCCCCCCCC).

I'm not sure why there are 192 bytes of seemingly dead space, but that might be VC++ building some guard space into your local variable area to try to detect stack smashing.

You will probably get a very different output if you switch from Debug to Release build.

0

精彩评论

暂无评论...
验证码 换一张
取 消