String 在nasm程序集中接受和打印两个字符串
我有以下代码:String 在nasm程序集中接受和打印两个字符串,string,assembly,printing,nasm,String,Assembly,Printing,Nasm,我有以下代码: section .data msg3 db 'Enter Two Strings: ' msg3Len equ $ -msg3 section .bss string1Len resb 1 string1 resb 0 string2Len resb 1 string2 resb 0 section .text global _start _start: mov eax,4 mov ebx,1 mov ecx,ms
section .data
msg3 db 'Enter Two Strings: '
msg3Len equ $ -msg3
section .bss
string1Len resb 1
string1 resb 0
string2Len resb 1
string2 resb 0
section .text
global _start
_start:
mov eax,4
mov ebx,1
mov ecx,msg3
mov edx,msg3Len
int 80h
mov eax,3
mov ebx,1
mov ecx,string1
int 80h
dec al
mov byte [string1Len], al
mov eax,3
mov ebx,1
mov ecx,string2
int 80h
dec al
mov byte [string2Len], al
mov eax,4
mov ebx,1
mov ecx,string1
mov edx,[string1Len]
int 80h
mov eax,4
mov ebx,1
mov ecx,string2
mov edx,[string2Len]
int 80h
mov eax, 0
mov ebx, 1
int 80h
我在打印两个字符串时遇到问题。它打印多余的字符和垃圾字符。此外,当我打印三个字符串时,它会打印过多的字符。当我的代码看起来正确时,它有什么问题?当您从stdin读取到
string1
和string2
时,您正在写入尚未分配的内存(至少不是为了这个目的)resb 0
将保留零字节的空间(=无空间)。您应该保留与预期读取的最长字符串大小相同的空间
另一个问题是,您正在从
string1Len
和string2Len
(mov-edx,[string1Len]
)读取32位,即使这些变量的大小只有一个字节-这意味着您将读取实际变量之外的3个字节。要么将变量设为DWORD(使用resd
),要么使用movzx
指令将字节零扩展为DWORD(例如movzx-edx,byte[string1Len]
)。正如@Michael所写的使用resd
或movzx
,这是一个更好的解决方法
我用Ubuntu 64位测试了它:
; Compile with: nasm -f elf twoString.asm
; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 twoString.o -o twoString
; Run with: ./twoString
SECTION .data
msg db 'Enter Two Strings: ', 0Ah
msgLen equ $ - msg
SECTION .bss
string1: resb 255
string2: resb 255
SECTION .text
global _start
_start:
;print msg
mov edx, msgLen
mov ecx, msg
mov ebx, 1
mov eax, 4
int 80h
mov edx, 255 ; number of bytes to read
mov ecx, string1 ; reserved space to store our input (known as a buffer)
mov ebx, 0 ; write to the STDIN file
mov eax, 3 ; invoke SYS_READ (kernel opcode 3)
int 80h
mov edx, 255 ; number of bytes to read
mov ecx, string2 ; reserved space to store our input (known as a buffer)
mov ebx, 0 ; write to the STDIN file
mov eax, 3 ; invoke SYS_READ (kernel opcode 3)
int 80h
mov edx, 255
mov ecx, string1
mov ebx, 1
mov eax, 4
int 80h
mov edx, 255
mov ecx, string2
mov ebx, 1
mov eax, 4
int 80h
mov ebx, 0 ; return 0 status on exit - 'No Errors'
mov eax, 1 ; invoke SYS_EXIT (kernel opcode 1)
int 80h
resb 0
保留零字节的空间(即完全没有空间)。我应该更改什么?我将所有resb 0更改为resb 1,它仍然打印垃圾字符。