0

I'm trying to understand the differences between the code compiles in different compilers. I compiled this simple C code in Visual Studio that community in 2015:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    for (int i = 0; i < 8; i++) {
        printf("%d", i);
    }
    return 0;
}

And when i looking at the assembly code out, there is something quite odd thesis code:

PUSH EBP        ;main prolog
MOV EBP,ESP
SUB ESP,0CC    ;The first question - why so many bits(0xcch)? 

PUSH EBX
PUSH ESI
PUSH EDI        ; save ebx,esi,edi

;from here is the odd parts - we move adress to edi (the stack adress) 
;And we actually reset the memory of the stack to CCCCCCCC 
LEA EDI,DWORD PTR SS:[EBP-CC]  
MOV ECX,33
MOV EAX,CCCCCCCC
REP STOS DWORD PTR ES:[EDI] ;memset(edi,cccccccc,33)

;start of the loop:
MOV DWORD PTR SS:[EBP-8],0                                  ; i =0
JMP SHORT LoopExRe.00FC17A0
MOV EAX,DWORD PTR SS:[EBP-8]  
ADD EAX,1
MOV DWORD PTR SS:[EBP-8],EAX
CMP EAX,8                           ; while i < 8 loop
JGE SHORT LoopExRe.00FC17B9
PUSH EAX
PUSH OFFSET LoopExRe.??_C@_02DPKJAMEF@?$CFd?$AA@            ; ASCII "%d"
CALL LoopExRe.00FC1320
ADD ESP,8
JMP SHORT LoopExRe.00FC1797         ; End of loop


XOR EAX,EAX                        ;return 0
POP EDI
POP ESI
POP EBX                            
ADD ESP,0CC                        ; restore edi,esi,ebx and stack state

;The third question - what is it and why do they put the two of these lines?
CMP EBP,ESP                       
CALL LoopExRe.00FC1113

MOV ESP,EBP                      ;main epilog
POP EBP
RETN                               

Strange things were:

  1. Compiler allocated a large amount of memory on the stack with no apparent reason?

  2. Compiler decided for some reason also format the memory amount above to the CC, why?

  3. Before exit we compare ebp with esp and we jump to a specific function with the result, what is it and why is that?

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
tim
  • 1
  • 1
  • 2
    `0xcccccccc` is a common pattern in Visual C++ debug builds. It's used to ease debugging stack problems. [This article on MSDN](https://msdn.microsoft.com/en-us/library/aa260966(v=vs.60).aspx) have a table listing four such common patterns and when/where they are used. Try looking at the output from a *release* build instead. – Some programmer dude Dec 19 '16 at 15:22
  • [There's also this table](http://www.nobugs.org/developer/win32/debug_crt_heap.html) for debug builds, but curiously it's missing the `0xCCCCCCCC` bitpattern. – Chris O Dec 19 '16 at 15:25
  • Thank you @Someprogrammerdude – tim Dec 19 '16 at 15:35
  • 1
    Possible duplicate of [Why is the stack filled with 0xCCCCCCCC](http://stackoverflow.com/questions/17644418/why-is-the-stack-filled-with-0xcccccccc) – Bo Persson Dec 19 '16 at 17:32

0 Answers0