问题
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?
回答1:
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.)
来源:https://stackoverflow.com/questions/64724666/x86-assembly-att-how-do-i-dynamically-allocate-memory-to-a-variable-at-runti