Declaring variable-sized arrays in assembly

余生长醉 提交于 2020-01-15 05:21:07

问题


I'm writing an assembly program which I want to be able to do the (basic) following:

x = 100;
y = int[x]

E.g. the size of y depends on the value of x.

NOTE: I am using NASM instruction set on a 64 bit Ubuntu system.

In assembly I know that the size of an array needs to be declared in the data section of the file e.g.

myvariable resq 1000

The problem is I won't know how big to make it till I have done a previous calculation. What I really want is something like:

mov rax, 100
myvariable resq rax

But that's not allowed right? Just having some confusion over array access/declarations in assembly.

Any pointers appreciated!


回答1:


Your C example is only possible if you declare the array on the stack or if you pull the memory from the heap with malloc or similar. For small values its perfectly fine (and faster) to use the stack:

mov rax, 100   # 100 elemtents
shl rax, 3     # muliply with 8, the size of an element
sub rsp, rax   # rsp points now to your array

# do something with the array
mov rbx, [rsp]    # load array[0] to rbx
mov [rsp+8], rbx  # store to array[1]

add rsp, rax   # rsp point to the return address again


来源:https://stackoverflow.com/questions/8504097/declaring-variable-sized-arrays-in-assembly

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