【发布时间】:2020-04-21 12:35:50
【问题描述】:
在我的代码中,我试图反向打印一个数组。 我的两个主要想法是要么使用堆栈和 LIFO 属性来执行此操作,要么使用循环作为从 10 到 0 的索引来反向访问元素。由于堆栈方法的对齐问题,我选择了第二个。
我对组装很陌生,希望能得到一些帮助,以了解我的错误在哪里。提前致谢!
DEFAULT REL
; external functions for inputs/outputs printf and scanf/printf
extern printf
extern scanf
section .data
prompt db "Entrez un entier : ",0
longIntFormat db "%ld",0
section .bss
entier resb 10 ; array of 10 integers
section.text
push rbp
mov rcx, 0
mov rdx, 0 ; initialise counter
lea rcx, [entier] ; load array into register rcx
; fills the array with user input
_getLoop:
; call printf
lea rdi,[prompt]
mov rax,0
call printf wrt ..plt
; call scanf
lea rdi,[longIntFormat]
lea rsi, [rcx + rdx] ; array + Index
mov rax,0
call scanf wrt ..plt
inc rdx ; inc. Index/counter
cmp rdx, 10
jl _getLoop ; While counter is less than 10 (size of array)
mov rcx, 0 ; set rcx to 0
mov rdx, 10 ; counter set to 10
lea rcx, [entier] ; load array into rcx
; print the array in reverse using the counter as Index
_printLoop:
; call printf
lea rdi, [rcx + rdx] ; rdi = [array + Index]
mov rax,0
call printf wrt ..plt
dec rdx
cmp rdx, 0 ; compare counter with 0
jge _printLoop ; Once 0 is reached the loop has gone through all the array
;restores registers
pop rbp
; returns 0 to C program
mov rax, 0
ret
【问题讨论】:
-
为什么你的
jl _getLoop后面有一个ret?这似乎过早地从函数中返回。 -
jl 之后的 ret 是错误的,应该保留原始值还是每次调用都对 rcx 和 rdx 有影响?我真的不知道 printf 和 scanf 来自哪个库,但如果这可以帮助它们被定义为
DEFAULT REL extern printf extern scanf -
您使用的是什么操作系统?不同系统上的调用约定不同。
-
你的代码被截断了吗?最后一条指令是
jge,但是如果没有跳转会发生什么?看到调用它的代码也很好;即完整的程序,包含构建和运行它所需的一切(包括用于构建它的命令!)。换句话说,minimal reproducible example. -
添加了代码的末尾,我真的不知道它可以运行什么,它用于分配,我正在基于 Web 的命令行上运行代码。应该是用YASM,因为我的课程就是基于它的
标签: assembly segmentation-fault x86-64 yasm