Here is a sample function reverse engineered from an easy program:main            proc nearvar_70          = dword ptr -70hvar_6C          = dword ptr -6Chvar_68          = dword ptr -68hi_2             = dword ptr -54hi               = dword ptr -4push    ebpmov     ebp, espand     esp, 0FFFFFFF0hsub     esp, 70hmov     [esp+70h+i], 0jmp     short loc_804840Aloc_80483F7:mov     eax, [esp+70h+i]mov     edx, [esp+70h+i]add     edx, edxmov     [esp+eax*4+70h+i_2], edxadd     [esp+70h+i], 1loc_804840A:cmp     [esp+70h+i], 13hjle     short loc_80483F7mov     [esp+70h+i], 0jmp     short loc_8048441loc_804841B:mov    eax, [esp+70h+i]mov    edx, [esp+eax*4+70h+i_2]mov    eax, offset aADD ; a[%d]=%d\nmov    [esp+70h+var_68], edxmov    edx, [esp+70h+i]mov    [esp+70h+var_6C], edxmov    [esp+70h+var_70], eaxcall   _printfadd    [esp+70h+i], 1loc_8048441:cmp    [esp+70h+i], 13hjle     short loc_804841Bmov    eax, 0leave retnmain   endpC code#include <stdio.h>int main() {    int a[20];    int i;    for (i=0; i<20; i++)        a[i]=i*2;    for (i=0; i<20; i++)        printf (a[%d]=%d\n, i, a[i]);    return 0;}My questions are:Why is memory not allocated consecutively and why are some parts of the memory in between esp + 70h -54h and esp + 70h -68h not used?In sub esp, 70h, the number 70h seems to be a random number in a different program, and it is often larger than we need. Why don't the compiler just allocate what we need?
Memory allocation on the stack
assembly;memory;stack variables
In your case because int is 4 bytes and you want 20 elementint a[20] // --> 20 * 4 = 0x50so it is very normal for i and i_2The other thing is that your compiler didn't push printf arguments into stack. It pre-allocated the stack location in var_70 = dword ptr -70hvar_6C = dword ptr -6Chvar_68 = dword ptr -68hand called the function like thismov    edx, [esp+eax*4+70h+i_2]mov    eax, offset aADD ; a[%d]=%d\nmov    [esp+70h+var_68], edxmov    edx, [esp+70h+i]mov    [esp+70h+var_6C], edxmov    [esp+70h+var_70], eaxcall   _printfBut there is 2 reason for such a thing (not your case)...The Compiler align the buffer for performance reasons and ease of cache.in addition unaligned buffers cause failure in some cases like Windows API calls and make debugging hard, so the compilers align every buffer to avoid this kind of failure.Some safe compilation allocate random number after buffers to prevent successful exploitation of buffer overruns. for example:and     esp, 0FFFFFFF0hyeap! as @DCoder commented, you asked it Here before.