Unused memory allocated on the stack for each usage of "new" in a function RRS feed

  • Question

  • This sample code:

    staticvoid DoWork4() {     var a = new object();     a = new object();     a = new object();     a = new object();     a = new object();     a = new object();     a = new object(); }

    Produces undesirable assembly in both x86 and x64 platforms (optimization is on), when compiled with VS13 Ultimate on W8.1 x64 bit machine.

    The assembly outputted looks like this:

                a = new object();
    00882687  mov         ecx,6D512554h  
    0088268C  call        00652100  
    00882691  mov         dword ptr [ebp-0Ch],eax  
    00882694  mov         ecx,dword ptr [ebp-0Ch]  
    00882697  call        6D410B40  
    0088269C  nop  
                a = new object();
    0088269D  mov         ecx,6D512554h  
    008826A2  call        00652100  
    008826A7  mov         dword ptr [ebp-10h],eax  
    008826AA  mov         ecx,dword ptr [ebp-10h]  
    008826AD  call        6D410B40  
    008826B2  nop  

    (and so on...)

    As you may see, many "local variables" are used here, in the given snippet, ebp-0x10 and ebp-0x0C are used. In the whole outputted assembly, more data on the stack is used, and the functions actually allocates 0x1C bytes (sub esp, 0x1C) on the stack!

    Similar output is given for x64 too.

    What is this variable used for? Why is per "new" keyword and not per allocation?

    This poses a problem for function that have many "new"-s in their code and may pose a limit on the length of functions.

    void StackOverflow() { StackOverflow(); }

    Thursday, May 21, 2015 9:50 PM


  • None of the current JIT compilers (x86, RyuJIT, x64 legacy JIT) produce that kind of code with optimization enabled. You're looking at debug code.
    Thursday, May 21, 2015 11:03 PM