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

穿精又带淫゛_ 提交于 2021-02-04 08:36:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!