Search code examples
assemblyx86gnu-assembleratt

x86 Assembly (AT&T): How do I dynamically allocate memory to a variable at runtime?


I am trying to allocate an amount of space to a variable at runtime. I know that I can allocate a constant amount of space to a variable at compile time, for instance:

.data
    variable: # Allocate 100 bytes for data
        .space 100

However, how do I allocate a variable amount of space to a variable at runtime? For instance, allocating %eax bytes of space to the variable at runtime?


Solution

  • You can't dynamically allocate static storage. You need to use the stack, or malloc / mmap / whatever (sometimes called the "heap"). (Unless you just make a huge array in the .bss, where you should have put this instead of .data, and only use however much you need. Lazy memory allocation by the kernel makes that fine.)

    You can keep a pointer in static storage, like C static int *p;, but then you need to go through the extra layer of indirection every time you access it.

    A variable-sized allocation on the stack is what compilers do for alloca, or for C99 variable-length arrays. Look at compiler output for how they round the allocation size up to a multiple of 16 to keep the stack aligned. (And how they address that storage relative to the new value of the stack pointer.)