首页 > 解决方案 > 在 NASM 中输入大字符串时出错

问题描述

  1. 我在 Linux 上使用 x64 NASM(Ubuntu 20.04,使用 Virtual Box)
  2. 我也在使用 SASM IDE,它包含内置的 io64 库(显然,这个库有助于控制台输入/输出)
  3. 我正在解决的任务是非常基本的:
  1. 这是我的代码
; NASM, x64, Linux, Ubuntu 20.04

%include "io64.inc"

section .text
global main
main:
        GET_STRING name, 101        ; reading name
        mov rax, 0                  ; initializing counter
        call input_iter             ; processing input
        mov byte [output + rax + 7], '!'        ; this character is needed by condition
        mov byte [output + rax + 8], 0xa
        mov rax, 0                  ; initializing counter
        call output_iter            ; giving output
        jmp end

input_iter: ; one iteration of input loop
        mov byte ch, [name + rax]
        mov byte [output + rax + 7], ch        ; writing one char from name to output
        inc rax
        cmp byte [name + rax], 0x0             ; GET_STRING ends string with 0-code char
        jne input_iter
        ret

output_iter: ; one iteration of output loop
        PRINT_CHAR [output + rax]        ; char given to out
        inc rax
        cmp byte [output + rax], 0xa     ; if char is NUL, iteration stops
        jne output_iter
        ret

end: ; just an end of program

section .data
output db 'Hello, ', 0xa ; here will be all output
name db 0xa              ; temporary storage for input   
  1. 现在的问题是:当输入为 16 个字符或更长时,程序会因错误而终止。15 个或更少的字符都可以。我不知道为什么!

PS 这是我在 Stackoverflow 上的第一个问题。我喜欢代码字段,这很有趣

标签: stringassemblynasmsasm

解决方案


您没有为输入/输出字符串保留足够的临时存储空间。
name db 0xa只为一个字节定义空间,并且无效地用 value 初始化它0xa。该值被 中的第一个字母覆盖GET_STRING name, 101。下一个字母存储在 . 后面的未定义内存中name。为部分分配的内存.data被四舍五入,因此可能在字节后面分配了几个字节,name并且您的程序意外地适用于短输入字符串。当字符串较长时,它会尝试访问未分配的内存,从而导致分段错误。

, 0xaoutput字符串定义中省略并替换name db 0xa
name: times 101 db 0x0a,请参阅NASM 中的重复数据
您可以output将 with打印name为一个连接的字符串。


推荐阅读