问题
I'm using a 64 bits Linux system, and I'm trying to use NASM to build a program that asks the user for input, and then prints it. Afterwards, the user can choose to do the same again, or exit.
My issue is that the variable 'text', which is used to store the user's input, is not reset at the end of each execution, so something like this happens:
User enters text the 1st time: Helloooooooooooooooooooooooooooooo
Output: Helloooooooooooooooooooooooooooooo
User enters text the 2nd time: Boom!
Output: Boom! oooooooooooooooooooooooooooo
Part of the "Helloooooo" from the first execution is showing up, and I don't know how to prevent that from happening.
I'd appreciate any help, as I'm just starting to learn about this.
Thanks
This is what I've done:
section .data
prompt db "Type your text here.", 0h
retry db "Wanna try again? If yes, enter y. If not, enter anything else to close the program", 0h
section .bss
text resb 255
choice resb 2
section .text
global _start
_start:
mov rax, 1 ;Just asking the user to enter input
mov rdi, 1
mov rsi, prompt
mov rdx, 21
syscall
mov rax, 0 ;Getting input and saving it on var text
mov rdi, 0
mov rsi, text
mov rdx, 255
syscall
mov rax, 1 ;Printing the user input
mov rdi, 1
mov rsi, text
mov rdx, 255
syscall
mov rax, 1 ;Asking if user wants to try again
mov rdi, 1
mov rsi, retry
mov rdx, 83
syscall
mov rax, 0 ;Getting input and saving it on var choice
mov rdi, 0
mov rsi, choice
mov rdx, 2
syscall
mov r8b, [choice] ;If choice is different from y, go to end and close the program. Otherwhise, go back to start.
cmp byte r8b, 'y'
jne end
jmp _start
end:
mov rax, 60
mov rdi, 0
syscall
回答1:
mov rax, 1 ;Printing the user input
mov rdi, 1
mov rsi, text
mov rdx, 255
syscall
You always write 255 characters, no matter how many were input. If the user input fewer than 255, you'll write whatever else happens to be in your text
buffer, possibly data left over from a previous iteration.
When you issue the read
system call (i.e. syscall
with rax=0
), it will return in rax
a value indicating the number of characters read (or 0 on end-of-file, or a negative number on error). Only that many characters have been written into the buffer; the rest of it is unchanged.
It's not necessary to "reset" the remaining contents of the buffer, and even if you write zeros over it or something, it will only result in you outputting a bunch of unwanted zero bytes - which in fact you already do. You may not see them on a terminal, but if you redirect your output to a file, they'll be there.
So you should pass the value returned from read
, if it's positive, in rdx
to write
(syscall with rax=1
) instead of always using 255. Then you will only write what was read, and the remaining contents of the buffer are irrelevant as they will not be used.
来源:https://stackoverflow.com/questions/63822095/reset-a-string-variable-to-print-multitple-user-inputs-in-a-loop-nasm-assembly