在程序集中声明可变大小的数组 [英] Declaring variable-sized arrays in assembly

查看:38
本文介绍了在程序集中声明可变大小的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个汇编程序,我希望能够执行以下(基本)操作:

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

x = 100;
y = int[x]

例如y 的大小取决于 x 的值.

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

注意:我在 64 位 Ubuntu 系统上使用 NASM 指令集.

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.

感谢任何指点!

推荐答案

只有在堆栈上声明数组或者使用 malloc 或类似方法从堆中提取内存时,您的 C 示例才有可能.对于较小的值,使用堆栈非常好(而且速度更快):

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

这篇关于在程序集中声明可变大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆