x86汇编程序退出状态码未按预期显示的问题求助
x86汇编查找列表最大值时退出状态码错误的问题分析与解决
问题根源
你的代码核心问题是当当前元素不大于当前最大值时,错误执行了setNewBiggestNum代码块,导致最后把列表末尾的0覆盖了原本正确的最大值5。
具体流程拆解
- 当循环到
eax=4时,edi=5,此时ebx=4,jg setNewBiggestNum触发,ebx被更新为5,随后跳回cmpLoop。 - 进入
cmpLoop后,cmp $0,%edi(此时edi=5)不相等,eax自增为5,edi被赋值为列表末尾的0。 - 执行
cmp %ebx,%edi(0 vs 5),jg条件不满足,程序不会跳转,会顺序执行setNewBiggestNum中的代码:把edi的0赋值给ebx,然后跳回cmpLoop。 - 再次进入
cmpLoop,cmp $0,%edi相等,跳转到printBiggestNum,此时ebx已经是0,所以退出状态码为0。
解决办法
在cmp %ebx,%edi之后,若不满足jg条件,直接跳回cmpLoop,跳过setNewBiggestNum代码块。只需添加一条jmp cmpLoop指令即可。
修正后的代码
.section .data list: .long 1, 2, 3, 4, 5, 0 .section .text .globl _start _start: movl $0,%eax # eax will save our current location movl list(,%eax,4),%edi movl %edi,%ebx # ebx will save the biggest number since it's the beginning - edi is the biggest cmpLoop: cmp $0,%edi je printBiggestNum incl %eax movl list(,%eax,4), %edi cmp %ebx,%edi jg setNewBiggestNum jmp cmpLoop # 添加该行,不更新最大值时直接回到循环开头 setNewBiggestNum: movl %edi,%ebx jmp cmpLoop printBiggestNum: movl $1,%eax int $0x80
内容的提问来源于stack exchange,提问作者user16713791
相关产品推荐
相关产品推荐

