在汇编语言分段错误 [英] Segmentation Fault in Assembly Language
问题描述
我learningn AT& T公司的x86汇编语言。我试图写一个汇编程序它接受一个整数n,然后返回结果(N / 2 + N / 3 + N / 4)。这里是我做了什么:
I am learningn AT&T x86 assembly language. I am trying to write an assembly program which takes an integer n, and then return the result (n/2+n/3+n/4). Here is what I have done:
.text
.global _start
_start:
pushl $24
call profit
movl %eax, %ebx
movl $1, %eax
int $0x80
profit:
popl %ebx
popl %eax
mov $0, %esi
movl $4, %ebp
div %ebp
addl %eax, %esi
movl %ecx, %eax
movl $3, %ebp
div %ebp
addl %eax, %esi
movl %ecx, %eax
movl $2, %ebp
div %ebp
addl %eax, %esi
movl %esi, %eax
cmpl %ecx, %esi
jg end
pushl %ebx
ret
end:
mov %ecx, %eax
ret
问题是我得到分段错误。问题出在哪里?
The problem is I am getting segmentation fault. Where is the problem?
推荐答案
我觉得code在这里失败:
I think the code fails here:
_start:
pushl $24
call profit
movl %eax, %ebx
movl $1, %eax
int $0x80
profit:
popl %ebx
popl %eax
所以,你推$ 24个
(4字节),然后呼叫利润
,这推 EIP
,并跳转到利润
。然后你弹出 EIP
的价值为 EBX
和值 $ 24个
到 EAX
。
So, you push $24
(4 bytes) and then call profit
, which pushes eip
and jumps to profit
. Then you pop the value of eip
into ebx
and the value $24
into eax
.
然后,在最后,如果 JG结束
分支结束:
,那么栈将不会举行一个有效的返回地址, RET
将失败。你可能需要 pushl%EBX
有太多。
Then, in the end, if jg end
branches to end:
, then the stack won't hold a valid return address and ret
will fail. You probably need pushl %ebx
there too.
cmpl %ecx, %esi
jg end
pushl %ebx
ret
end:
mov %ecx, %eax
; `pushl %ebx` is needed here!
ret
这篇关于在汇编语言分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!