Alloca implementation

前端 未结 11 983
误落风尘
误落风尘 2020-11-29 08:50

How does one implement alloca() using inline x86 assembler in languages like D, C, and C++? I want to create a slightly modified version of it, but first I need to know how

11条回答
  •  遥遥无期
    2020-11-29 09:42

    alloca is directly implemented in assembly code. That's because you cannot control stack layout directly from high level languages.

    Also note that most implementation will perform some additional optimization like aligning the stack for performance reasons. The standard way of allocating stack space on X86 looks like this:

    sub esp, XXX
    

    Whereas XXX is the number of bytes to allcoate

    Edit:
    If you want to look at the implementation (and you're using MSVC) see alloca16.asm and chkstk.asm.
    The code in the first file basically aligns the desired allocation size to a 16 byte boundary. Code in the 2nd file actually walks all pages which would belong to the new stack area and touches them. This will possibly trigger PAGE_GAURD exceptions which are used by the OS to grow the stack.

提交回复
热议问题