在汇编语言分段错误 [英] Segmentation Fault in Assembly Language

查看:162
本文介绍了在汇编语言分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我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屋!

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