【发布时间】:2015-11-21 12:17:23
【问题描述】:
我已经问过一个问题,人们向我指出了一个整数到字符串转换的线程。反之亦然。我只是暂时复制了它,以便查看我的程序是否有效,稍后我将尝试编写自己的程序。但是有一个问题。我找不到我犯的错误。在最后一次输入之后,程序总是以 Segmentation Fault 退出。我尝试删除 int 到字符串的转换,只显示输入的值并且它有效。所以我必须在转换中做错了什么。这是我的第一个程序之一,如果我想进一步进步,我真的需要了解它为什么行不通。谢谢你。这是我的代码:
section .text
global _start
_start:
mov edx, lenask
mov ecx, ask
mov ebx, 1
mov eax, 4
int 0x80
mov edx, 5
mov ecx, input
mov ebx, 0
mov eax, 3
int 0x80
mov edx, lenask2
mov ecx, ask2
mov ebx, 1
mov eax, 4
int 0x80
mov edx, 5
mov ecx, input2
mov ebx, 0
mov eax, 3
int 0x80
lea esi, [input]
mov ecx, 2
call string_to_int
push eax
lea esi, [input2]
mov ecx, 4
call string_to_int
mov ebx, eax
pop eax
neg eax
add ebx, eax
mov [buffer], ebx
mov eax, [buffer]
lea esi, [result]
call int_to_string
mov edx, lenanswer
mov ecx, answer
mov ebx, 1
mov eax, 4
int 0x80
mov edx, 5
mov ecx, result
mov ebx, 1
mov eax, 4
int 0x80
mov eax, 1
mov ebx, 0
int 80h
;code taken from another thread
; Input:
; EAX = integer value to convert
; ESI = pointer to buffer to store the string in (must have room for at least 10 bytes)
; Output:
; EAX = pointer to the first character of the generated string
int_to_string:
add esi,9
mov byte [esi], 0
mov ebx,10
.next_digit:
xor edx,edx ; Clear edx prior to dividing edx:eax by ebx
div ebx ; eax /= 10
add dl,'0' ; Convert the remainder to ASCII
dec esi ; store characters in reverse order
mov [esi],dl
test eax,eax
jnz .next_digit ; Repeat until eax==0
mov eax,esi
push eax
ret
;code taken from another thread
; Input:
; ESI = pointer to the string to convert
; ECX = number of digits in the string (must be > 0)
; Output:
; EAX = integer value
string_to_int:
xor ebx,ebx ; clear ebx
.next_digit:
movzx eax,byte[esi]
inc esi
sub al,'0' ; convert from ASCII to number
imul ebx,10
add ebx,eax ; ebx = ebx*10 + eax
loop .next_digit ; while (--ecx)
mov eax,ebx
ret
section .data
ask db "What is your age?"
lenask equ $-ask
ask2 db "What is today's year?"
lenask2 equ $-ask2
answer db "The age you were born was: "
lenanswer equ $-answer
section .bss
input resw 5
input2 resw 5
buffer resw 5
result resw 10
一个例子:
What is your age?35
What is today's year?2015
The age you were born was: Segmentation fault(core dumped)
应该做的:
What is your age?35
What is today's year?2015
The age you were born was: 1980
谢谢!
【问题讨论】:
-
读取固定字节可能是错误的。您可能应该每个
int 0x80只读取一个字节并检查代表数据结尾的“\n”。 -
int_to_string的结尾肯定看起来很糟糕:push eax; ret这可能是错误的地方。你应该学会使用调试器,也不要在不懂代码的情况下盲目复制代码。 -
尝试在代码末尾添加一个空行。一些编译器想要这样。
-
@Jester,我负部分责任。这个人昨天问了一个问题,我发表了评论并将他们定向到这个SO Answer,但我没有跟进他们,因为我很忙。原代码没有push
标签: linux assembly io x86 nasm