I have already asked a question and people pointed me to a thread of interger to string conv. and vice versa. I just copied it for now so I can see if my program works, and I'll try and write my own later. But there's a problem.I can't find a mistake I've done. The program always exits with Segmentation Fault after the last input. I tried removing the int to string conversion and just display the inputted values and it worked. So I must've done something wrong with the conversion. It's one of my first programs and I really need to understand why it won't work If I want to progress any further. Thank you. Here is my code:
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
An example of what happens:
What is your age?35
What is today's year?2015
The age you were born was: Segmentation fault(core dumped)
It should have done:
What is your age?35
What is today's year?2015
The age you were born was: 1980
Thank you!