Reputation: 5447
I wrote the following code in order to fill an array with the numeric strings 9876..1234
:
segment .data
counter dd 9877
count dd 8642
array times 9876 dd '0000'
segment .bss
buffer resb 4
segment .text
global _start
_start:
mov ecx, [count]
mov edx, array
mov dword [pointer], array
l1:
push ecx
push edx
dec dword [counter] ; decrease the counter
lea esi, [buffer]
mov eax, [counter]
call int_to_string
mov ecx, eax ; "begin print" position
xor edx, edx
getlen:
cmp byte [ecx + edx], 10
jz gotlen
inc edx
jmp getlen
gotlen:
inc edx
push eax ; printing the string converted
mov eax, 4
mov ebx, 1
int 0x80
pop eax ; printing the string converted
pop edx ; copying the string to array
mov [edx], eax
add edx, 4
pop ecx
loop l1
mov ecx, [count] ;printing the array
mov eax, array
l2:
push ecx
mov [pointer], eax
push eax
mov eax, 4
mov ebx, 1
mov ecx, pointer
mov edx, 4
int 0x80
pop eax
add eax, 4
pop ecx
loop l2
mov eax, 1
mov ebx, 0
int 0x80
int_to_string:
add esi, 9 ; counter + 9 ?
mov byte [esi], 10
mov ebx, 10
.next_digit:
xor edx, edx
div ebx
add dl, '0'
dec esi
mov [esi],dl
test eax, eax
jnz .next_digit
mov eax, esi
ret
Printing out causes random characters to be printed on the screen. What would cause this in my code?
Upvotes: 0
Views: 2163
Reputation: 14409
Three central errors:
1) "buffer" is too small & pointer is missing.
Change
segment .bss
buffer resb 4
to
segment .bss
buffer resb 10
pointer resd 1
2) "copying" is wrong.
Change
pop eax ; printing the string converted
pop edx ; copying the string to array
mov [edx], eax
add edx, 4
to
pop eax ; printing the string converted
mov eax, [eax]
pop edx ; copying the string to array
mov [edx], eax
add edx, 4
3) "printing" is wrong.
Change
mov eax, 4
mov ebx, 1
mov ecx, pointer
mov edx, 4
int 0x80
to
mov eax, 4
mov ebx, 1
mov ecx, [pointer]
mov edx, 4
int 0x80
Upvotes: 1